local extension = Package("rfenghou_fuyao")
extension.extensionName = "aaa_fenghou"

local U = require "packages/utility/utility"
local DIY = require "packages/diy_utility/diy_utility"
local RUtil = require "packages/aaa_fenghou/utility/rfenghou_util"

Fk:loadTranslationTable{
  ["rfenghou_fuyao"] = "扶摇",
  ["fuyao"] = "扶摇",
  ["fuyaoz"] = "扶摇",
  ["rfenghouif"] = "if",
}
Fk:appendKingdomMap("god", {"fuyao"})

local jisi = General:new(extension, "rfenghou__jisi", "fuyao", 4)
local baijiangdengwang = fk.CreateTriggerSkill{
  name = "rfenghou__baijiangdengwang",
  anim_type = "masochism",
  events = {fk.GameStart, fk.Damaged},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.GameStart then
        return true
      elseif event == fk.Damaged then
        return target == player
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local record = room:getTag("rfenghou__baijiangdengwang_recod")
    if record == nil then
      record = {generals = {}, hall_of_fame = {}, kingdoms = {}}
      for packageName, package in pairs(Fk.packages) do
        if package.extensionName == "aaa_fenghou" or package.extensionName == "aaa_fengqi" then
          for _, general in ipairs(package.generals) do
            table.insertIfNeed(record.kingdoms, general.kingdom)
            if packageName == "rfenghou_hall_of_fame" then
              table.insert(record.hall_of_fame, general.name)
            elseif Fk:canUseGeneral(general.name) then
              table.insert(record.generals, general.name)
            end
          end
        end
      end
      room:setTag("rfenghou__baijiangdengwang_recod", record)
    end
    local generals = table.simpleClone(record.generals)
    if #player:getTableMark(self.name.."_kingdom") >= #record.kingdoms then
      table.insertTable(generals, record.hall_of_fame)
    end

    if #generals == 0 then return end
    local existingGenerals = {"rfenghou__jisi"}
    for _, p in ipairs(room.players) do
      table.insert(existingGenerals, p.general)
      table.insert(existingGenerals, p.deputyGeneral)
    end
    generals = table.filter(generals, function (name) return not table.contains(existingGenerals, name) end)
    generals = table.random(generals, 3)
    
    local general = room:askForGeneral(player, generals, 1, true)---@type string
    room:addTableMarkIfNeed(player, self.name, Fk.generals[general].kingdom)
    room:changeHero(player, general, false, true, true, false, false)
  end,
}
local fengqifuyao = fk.CreateTriggerSkill{
  name = "rfenghou__fengqifuyao$",
  anim_type = "special",
  events = {fk.Death},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target.kingdom:startsWith("fuyao")
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#rfenghou__fengqifuyao-invoke:::"..target.general)
  end,
  on_use = function(self, event, target, player, data)
    player.room:changeHero(player, target.general, false, true, true, false, false)
  end,
}
jisi:addSkill(baijiangdengwang)
jisi:addSkill(fengqifuyao)
Fk:loadTranslationTable{
  ["rfenghou__jisi"] = "祭祀黄泉Romantic",
  ["#rfenghou__jisi"] = "萦名神亭",
  ["designer:rfenghou__jisi"] = "zzcclll朱苦力",
  --["illustrator:rfenghou__jisi"] = "",

  ["rfenghou__baijiangdengwang"] = "拜将登王",
  [":rfenghou__baijiangdengwang"] = "游戏开始时，或受到伤害后，你可以从“封侯”、“风起”包中变更一次副将，所有势力的武将均变更过后，此后发现池中增加"..
  "荣誉室武将！",
  ["rfenghou__fengqifuyao"] = "风起扶摇",
  [":rfenghou__fengqifuyao"] = "主公技，“扶摇”势力的角色死亡时，你可以将其武将牌替换为你的副将。",
  ["#rfenghou__fengqifuyao-invoke"] = "风起扶摇：是否将副将变为 %arg？",
}

local zhukuli = General:new(extension, "rfenghou__zhukuli", "fuyaoz", 5)
local shejili = fk.CreateTriggerSkill{
  name = "rfenghou__shejili",
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished, fk.PreHpRecover, fk.PreCardEffect},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.CardUseFinished then
        if target == player and table.contains({"peach", "analeptic"}, data.card.trueName) and
          not table.contains(data.card.skillNames, self.name) and not player:isNude() then
          local name = data.card.trueName == "analeptic" and "peach" or "analeptic"
          return not player:prohibitUse(Fk:cloneCard(name)) and not player:isProhibited(player, Fk:cloneCard(name))
        end
      elseif event == fk.PreHpRecover then
        return target == player and data.num > (player.maxHp - player.hp)
      elseif event == fk.PreCardEffect then
        return data.to == player.id and table.contains({"peach", "god_salvation"}, data.card.trueName) and not player:isWounded()
        --一般而言不存在未受伤而回复体力的酒，所以偷懒！
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUseFinished then
      local name = data.card.trueName == "analeptic" and "peach" or "analeptic"
      local cards = table.filter(player:getCardIds("he"), function (id)
        local card = Fk:cloneCard(name)
        card.skillName = self.name
        card:addSubcard(id)
        return not player:prohibitUse(Fk:cloneCard(name)) and not player:isProhibited(player, Fk:cloneCard(name))
      end)
      if #cards > 0 then
        local id = room:askForCard(player, 1, 1, true, self.name, false, tostring(Exppattern{ id = cards }),
          "#rfenghou__shejili-ask:::"..name)
        local card = Fk:cloneCard(name)
        card.skillName = self.name
        card:addSubcards(id)
        local use = {
          card = card,
          from = player.id,
          tos = {{player.id}},
          extraUse = true,
        }
        if name == "analeptic" and player.dying then
          use.extra_data = {
            analepticRecover = true
          }
        end
        room:useCard(use)
      end
    else
      local n = 0
      if event == fk.PreHpRecover then
        n = data.num - (player.maxHp - player.hp)
      elseif event == fk.PreCardEffect then
        n = 1 + (data.additionalRecover or 0)
      end
      if n > 0 then
        local cards = room:getCardsFromPileByRule("slash,jink", n, "discardPile")
        if #cards > 0 then
          room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
        end
      end
    end
  end,
}
local youxili = fk.CreateViewAsSkill{
  name = "rfenghou__youxili",
  anim_type = "control",
  pattern = "dismantlement",
  prompt = function ()
    return "#rfenghou__youxili:::"..(Self:getHandcardNum() - Self:getMaxCards())
  end,
  card_filter = function(self, to_select, selected)
    return Fk:currentRoom():getCardArea(to_select) == Card.PlayerHand and #selected < (Self:getHandcardNum() - Self:getMaxCards())
  end,
  view_as = function(self, cards)
    if #cards ~= (Self:getHandcardNum() - Self:getMaxCards()) then return end
    local c = Fk:cloneCard("dismantlement")
    c.skillName = self.name
    c:addSubcards(cards)
    return c
  end,
  enabled_at_play = function (self, player)
    return player:getHandcardNum() > player:getMaxCards() and player:usedSkillTimes(self.name, Player.HistoryRound) == 0
  end,
  enabled_at_response = function(self, player, response)
    return not response and player:getHandcardNum() > player:getMaxCards() and
      player:usedSkillTimes(self.name, Player.HistoryRound) == 0
  end,

  on_acquire = function (self, player, is_start)
    local room = player.room
    for _, p in ipairs(room:getOtherPlayers(player)) do
      room:handleAddLoseSkills(p, "rfenghou__youxili&", nil, false, true)
    end
  end,
  on_lose = function (self, player, is_death)
    local room = player.room
    if not table.find(room:getOtherPlayers(player), function (p)
      return p:hasSkill(self, true)
    end) then
      for _, p in ipairs(room:getOtherPlayers(player)) do
        room:handleAddLoseSkills(p, "-rfenghou__youxili&", nil, false, true)
      end
    end
  end,
}
local youxili_targetmod = fk.CreateTargetModSkill{
  name = "#rfenghou__youxili_targetmod",
  extra_target_func = function(self, player, skill, card)
    if card and skill.trueName == "dismantlement_skill" and table.contains(card.skillNames, "rfenghou__youxili") then
      return #card.subcards - 1
    end
  end,
}
local YouxiliFunc = function (player)
  return table.filter(Fk:currentRoom().alive_players, function (p)
    if p ~= player and p:hasSkill(youxili) and p:getMark("rfenghou__youxili-round") == 0 then
      local n = p:getMaxCards() - p:getHandcardNum()
      return n > 0 and player:getHandcardNum() >= n
    end
  end)
end
local youxili_viewas = fk.CreateViewAsSkill{
  name = "rfenghou__youxili&",
  pattern = "nullification",
  prompt = function (self, selected_cards, selected)
    local src = YouxiliFunc(Self)
    if #src > 0 then
      return "#rfenghou__youxili&:"..src[1].id.."::"..(src[1]:getMaxCards() - src[1]:getHandcardNum())
    end
  end,
  card_filter = function (self, to_select, selected)
    return table.find(YouxiliFunc(Self), function (p)
      return #selected < p:getMaxCards() - p:getHandcardNum()
    end)
  end,
  view_as = function(self, cards)
    if not table.find(YouxiliFunc(Self), function (p)
      return #cards == p:getMaxCards() - p:getHandcardNum()
    end) then return end
    self.cost_data = cards
    local card = Fk:cloneCard("nullification")
    card.skillName = self.name
    return card
  end,
  before_use = function (self, player, use)
    local room = player.room
    local to
    local targets = table.filter(YouxiliFunc(Self), function (p)
      return #self.cost_data == p:getMaxCards() - p:getHandcardNum()
    end)
    if #targets == 1 then
      to = targets[1]
    elseif #targets > 1 then
      to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#rfenghou__youxili-give", self.name, false)
    end
    if to then
      room:setPlayerMark(to, "rfenghou__youxili-round", 1)
      room:moveCardTo(self.cost_data, Card.PlayerHand, to, fk.ReasonGive, self.name, nil, false, player.id)
    else
      return self.name
    end
  end,
  enabled_at_play = Util.FalseFunc,
  enabled_at_response = function (self, player, response)
    return not response and #YouxiliFunc(player) > 0
  end,
}
Fk:addSkill(youxili_viewas)
youxili:addRelatedSkill(youxili_targetmod)
zhukuli:addSkill(shejili)
zhukuli:addSkill(youxili)
Fk:loadTranslationTable{
  ["rfenghou__zhukuli"] = "朱苦力",
  ["#rfenghou__zhukuli"] = "猪",
  ["designer:rfenghou__zhukuli"] = "秀丽",
  --["illustrator:rfenghou__zhukuli"] = "",

  ["rfenghou__shejili"] = "超绝设计力",
  [":rfenghou__shejili"] = "锁定技，你未因此使用【桃】或【酒】后，须将一张牌当另一张使用；你能溢出上限回复体力，且改为获得弃牌堆中等量的"..
  "【杀】或【闪】。",
  ["rfenghou__youxili"] = "超强游戏力",
  [":rfenghou__youxili"] = "每轮各限一次，其他角色可以交给你能补至手牌上限张的手牌，以视为使用【无懈可击】；你可以将溢出手牌上限的手牌"..
  "当指定至多等量目标数的【过河拆桥】使用。",
  ["#rfenghou__shejili-ask"] = "超绝设计力：你需将一张牌当【%arg】使用",
  ["rfenghou__youxili&"] = "超强游戏力",
  [":rfenghou__youxili&"] = "每轮所有角色限一次，你可以交给朱苦力手牌使其手牌补至手牌上限，以视为使用【无懈可击】。",
  ["#rfenghou__youxili"] = "超强游戏力：你可以将%arg张手牌当指定至多等量目标的【过河拆桥】使用",
  ["#rfenghou__youxili&"] = "超强游戏力：你可以交给 %src %arg张手牌以视为使用【无懈可击】",
}

local yidaju = General:new(extension, "rfenghou__yidaju", "fuyao", 4)
local dajiaohuan = fk.CreateTriggerSkill{
  name = "rfenghou__dajiaohuan",
  events = {fk.EventPhaseStart},
  anim_type = "offensive",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase > 1 and player.phase < 8
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local judge = {
      who = target,
      reason = self.name,
      pattern = ".|.|spade,club,diamond",
    }
    room:judge(judge)
    if judge.card.suit == Card.Heart then
      player:chat("啊啊啊啊啊啊啊啊啊啊！")
    else
      local card = {room.draw_pile[1]}
      if #card > 0 then
        U.askForUseRealCard(room, player, card, nil, self.name,
          "#rfenghou__dajiaohuan-use", {
            bypass_times = true,
            extraUse = true,
            expand_pile = card,
          }, false, true)
      end
    end
  end,
}
for i = 1, 10, 1 do
  local yidaju_ = General:new(extension, "rfenghou"..i.."_yidaju", "fuyao", 4)
  yidaju_.total_hidden = true
end
local lianxuju = fk.CreateTriggerSkill{
  name = "rfenghou__lianxuju",
  anim_type = "control",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      local room = player.room
      local dat = {}
      room.logic:getEventsOfScope(GameEvent.Phase, 1, function (e)
        if e.data[1] == player then
          table.insert(dat, {e.id, e.end_id})
        end
      end, Player.HistoryTurn)
      if #dat == 0 then return end
      local n = 0
      for _, info in ipairs(dat) do
        if #room.logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
          return e.id >= info[1] and e.id <= info[2] and e.data[1].from == player.id
        end, Player.HistoryTurn) > 0 then
          n = n + 1
        end
      end
      if n > 0 then
        self.cost_data = n
        return true
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local n = self.cost_data
    local tos = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, n,
      "#rfenghou__lianxuju-choose:::"..n, self.name, true)
    if #tos > 0 then
      room:sortPlayersByAction(tos)
      self.cost_data = {tos = tos}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(self.cost_data.tos) do
      local p = room:getPlayerById(id)
      p.general = "rfenghou"..math.random(1, 10).."_yidaju"
      room:broadcastProperty(p, "general")
      room:handleAddLoseSkills(p, "rfenghou__dajudao", nil, true, false)
    end
  end,
}
local dajudao = fk.CreateTriggerSkill{
  name = "rfenghou__dajudao",
  anim_type = "control",
  events = {fk.AskForRetrial},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and not player:isNude() and data.reason == "rfenghou__dajiaohuan"
  end,
  on_cost = function(self, event, target, player, data)
    local cards = player.room:askForCard(player, 1, 1, true, self.name, true, ".|.|spade,club",
      "#rfenghou__dajudao-ask::" .. target.id)
    if #cards == 1 then
      self.cost_data = {cards = cards}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local card = Fk:getCardById(self.cost_data.cards[1])
    player.room:retrial(card, player, data, self.name, true)
  end,
}
yidaju:addSkill(dajiaohuan)
yidaju:addSkill(lianxuju)
yidaju:addRelatedSkill(dajudao)
Fk:loadTranslationTable{
  ["rfenghou__yidaju"] = "易大剧",
  ["#rfenghou__yidaju"] = "长恨离亭",
  ["designer:rfenghou__yidaju"] = "妙啊",
  --["illustrator:rfenghou__yidaju"] = "",

  ["rfenghou__dajiaohuan"] = "大叫唤",
  [":rfenghou__dajiaohuan"] = "阶段开始时，你进行一次判定，若结果不为<font color='red'>♥</font>，你可以使用牌堆顶的一张牌；"..
  "若结果为<font color='red'>♥</font>，你啊啊啊啊啊啊啊啊啊啊！",
  ["rfenghou__lianxuju"] = "连续剧",
  [":rfenghou__lianxuju"] = "回合结束时，你可以令X名角色的名字替换为易？剧，并获得〖大剧道〗。"..
  "（X为你本回合使用过牌的阶段数）",
  ["rfenghou__dajudao"] = "大剧道",
  [":rfenghou__dajudao"] = "〖大叫唤〗判定生效前，你可以打出一张黑色牌替换判定牌！",
  ["#rfenghou__dajiaohuan-use"] = "大叫唤：你可以使用这张牌",
  ["#rfenghou__lianxuju-choose"] = "连续剧：你可以令至多%arg名角色变为易X剧！",
  ["rfenghou1_yidaju"] = "易小剧",
  ["rfenghou2_yidaju"] = "易尖剧",
  ["rfenghou3_yidaju"] = "易太剧",
  ["rfenghou4_yidaju"] = "易犬剧",
  ["rfenghou5_yidaju"] = "易喜剧",
  ["rfenghou6_yidaju"] = "易悲剧",
  ["rfenghou7_yidaju"] = "易天剧",
  ["rfenghou8_yidaju"] = "易夭剧",
  ["rfenghou9_yidaju"] = "易京剧",
  ["rfenghou10_yidaju"] = "易黄梅戏",
  ["#rfenghou__dajudao-ask"] = "大剧道：你可以打出一张黑色牌替换 %dest 的〖大叫唤〗判定！",
}

local baixiaobei = General:new(extension, "rfenghou__baixiaobei", "fuyao", 3)
local siba = fk.CreateActiveSkill{
  name = "rfenghou__siba",
  anim_type = "control",
  prompt = "#rfenghou__siba",
  card_num = 0,
  target_num = 1,
  interaction = UI.ComboBox {choices = {
    "rfenghou__siba_xiyingxi",
    "rfenghou__siba_hushi",
    "rfenghou__siba_zhaoyu",
    "rfenghou__siba_lishu",
  }},
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function (self, to_select, selected)
    if self.interaction.data == "rfenghou__siba_xiyingxi" then
      return false
    elseif self.interaction.data == "rfenghou__siba_hushi" then
      return false
    elseif self.interaction.data == "rfenghou__siba_zhaoyu" then
      local card = Fk:getCardById(to_select)
      return #selected == 0 and (card.trueName == "slash" or card.trueName == "jink")
    elseif self.interaction.data == "rfenghou__siba_lishu" then
      return #selected < 4
    end
  end,
  target_filter  = function (self, to_select, selected, selected_cards, _, _, player)
    if self.interaction.data == "rfenghou__siba_xiyingxi" then
      local card = Fk:cloneCard("sincere_treat")
      card.skillName = self.name
      return card.skill:targetFilter(to_select, {}, {}, card, {bypass_distances = true}, player)
    elseif self.interaction.data == "rfenghou__siba_hushi" then
      return #selected == 0 and Fk:currentRoom():getPlayerById(to_select):canMoveCardsInBoardTo(player)
    elseif self.interaction.data == "rfenghou__siba_zhaoyu" then
      return false
    elseif self.interaction.data == "rfenghou__siba_lishu" then
      return false
    end
  end,
  feasible = function (self, selected, selected_cards)
    if self.interaction.data == "rfenghou__siba_xiyingxi" then
      local card = Fk:cloneCard("sincere_treat")
      card.skillName = self.name
      return #selected_cards == 0 and card.skill:feasible(selected, {}, Self, card)
    elseif self.interaction.data == "rfenghou__siba_hushi" then
      return #selected_cards == 0 and #selected == 1
    elseif self.interaction.data == "rfenghou__siba_zhaoyu" then
      return #selected_cards == 1 and #selected == 0
    elseif self.interaction.data == "rfenghou__siba_lishu" then
      return #selected_cards == 4 and #selected == 0
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local orig_info = {"general", player.general}
    local str = "xiaobai__"..string.sub(self.interaction.data, 16)
    if Fk.generals[str] then
      if player.deputyGeneral ~= nil and player.deputyGeneral == "rfenghou__baixiaobei" then
        orig_info = {"deputy", player.deputyGeneral}
        player.deputyGeneral = str
        room:broadcastProperty(player, "deputyGeneral")
      else
        player.general = str
        room:broadcastProperty(player, "general")
      end
    end
    if self.interaction.data == "rfenghou__siba_xiyingxi" then
      local card = Fk:cloneCard("sincere_treat")
      card.skillName = self.name
      room:useCard{
        from = player.id,
        tos = table.map(effect.tos, function(id) return {id} end),
        card = card,
      }
    elseif self.interaction.data == "rfenghou__siba_hushi" then
      local target = room:getPlayerById(effect.tos[1])
      room:askForMoveCardInBoard(player, target, player, self.name, nil, target)
    elseif self.interaction.data == "rfenghou__siba_zhaoyu" then
      local name = Fk:getCardById(effect.cards[1]).trueName
      room:recastCard(effect.cards, player, self.name)
      if player.dead then return end
      if name == "slash" then
        room:addPlayerMark(player, "@@rfenghou__siba_jink", 1)
      elseif name == "jink" then
        room:addPlayerMark(player, "@@rfenghou__siba_slash", 1)
      end
    elseif self.interaction.data == "rfenghou__siba_lishu" then
      room:recastCard(effect.cards, player, self.name)
      local cards = table.filter(effect.cards, function (id)
        return Fk:getCardById(id).trueName == "slash" and table.contains(room.discard_pile, id)
      end)
      local used = {}
      while not player.dead and #cards > 0 do
        cards = table.filter(effect.cards, function (id)
          return Fk:getCardById(id).trueName == "slash" and table.contains(room.discard_pile, id) and
            not table.contains(used, id)
        end)
        if table.find(cards, function (id)
          local card = Fk:getCardById(id)
          return player:canUse(card, {bypass_times = false})
        end) then
          local use = U.askForUseRealCard(room, player, cards, "slash", self.name, "#rfenghou__siba-slash", {
            bypass_times = false,
            extraUse = false,
            expand_pile = cards,
          }, false, false)
          if use then
            table.insert(used, use.card.id)
          end
        else
          break
        end
      end
    end
    if Fk.generals[str] then
      if orig_info[1] == "deputy" then
        player.deputyGeneral = orig_info[2]
        room:broadcastProperty(player, "deputyGeneral")
      else
        player.general = orig_info[2]
        room:broadcastProperty(player, "general")
      end
    end
  end,
}
local siba_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou__siba_trigger",
  mute = true,
  events = {fk.PreCardEffect},
  can_trigger = function(self, event, target, player, data)
    return player:getMark("@@rfenghou__siba_"..data.card.trueName) > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("rfenghou__siba")
    room:notifySkillInvoked(player, "rfenghou__siba", "control")
    room:doIndicate(player.id, {target.id})
    room:setPlayerMark(player, "@@rfenghou__siba_"..data.card.trueName, 0)
    return true
  end,
}
local zhuanhuan = fk.CreateTriggerSkill{
  name = "rfenghou__zhuanhuan",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if target == player and player.phase == Player.Start then
        return not player:isNude()
      elseif target ~= player and target.phase == Player.Finish then
        return not target.dead and not target:isNude()
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local suit = player:getTableMark("@rfenghou__zhuanhuan")[1]
    local pattern = ".|.|"..U.ConvertSuit(suit, "sym", "str")
    local card = player.room:askForDiscard(target, 1, 1, true, self.name, true, pattern,
      "#rfenghou__zhuanhuan-ask:"..player.id.."::"..suit, true)
    if #card > 0 then
      self.cost_data = {cards = card}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(target.id, {player.id})
    local mark = player:getTableMark("@rfenghou__zhuanhuan")
    local suit = mark[1]
    table.remove(mark, 1)
    table.insert(mark, suit)
    room:setPlayerMark(player, "@rfenghou__zhuanhuan", mark)
    room:throwCard(self.cost_data.cards, self.name, target, target)
    if player.dead then return end
    room:askForUseActiveSkill(player, "rfenghou__siba", "#rfenghou__siba", true)
  end,

  on_acquire = function (self, player, is_start)
    player.room:setPlayerMark(player, "@rfenghou__zhuanhuan", {"log_heart", "log_spade", "log_club", "log_diamond"})
  end,
  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@rfenghou__zhuanhuan", 0)
  end,
}
siba:addRelatedSkill(siba_trigger)
baixiaobei:addSkill(siba)
baixiaobei:addSkill(zhuanhuan)
Fk:loadTranslationTable{
  ["rfenghou__baixiaobei"] = "白小贝",
  ["#rfenghou__baixiaobei"] = "黑大壳",
  ["designer:rfenghou__baixiaobei"] = "胖即是胖",
  --["illustrator:rfenghou__baixiaobei"] = "",

  ["rfenghou__siba"] = "四八",
  [":rfenghou__siba"] = "出牌阶段限一次，你可以选择一项：1.视为使用一张无距离限制的【推心置腹】；2.将场上的一张牌移至你的场上；"..
  "3.重铸一张【杀】/【闪】并令被使用的下一张【闪】/【杀】无效；4.重铸四张牌并使用其中的【杀】（计入次数）。",
  ["rfenghou__zhuanhuan"] = "转换",
  [":rfenghou__zhuanhuan"] = "转换技，你的准备阶段或其他角色的结束阶段，当前回合角色可以弃置一张①<font color='red'>♥</font>②♠③♣"..
  "④<font color='red'>♦</font>牌并令你发动〖四八〗。",
  ["#rfenghou__siba"] = "四八：你可以执行一项",
  ["rfenghou__siba_xiyingxi"] = "视为使用一张无距离限制的【推心置腹】",
  ["rfenghou__siba_hushi"] = "将场上的一张牌移至你的场上",
  ["rfenghou__siba_zhaoyu"] = "重铸一张【杀】/【闪】并令被使用的下一张【闪】/【杀】无效",
  ["rfenghou__siba_lishu"] = "重铸四张牌并使用其中的【杀】",
  ["@@rfenghou__siba_slash"] = "四八 杀无效",
  ["@@rfenghou__siba_jink"] = "四八 闪无效",
  ["#rfenghou__siba-slash"] = "四八：请使用其中的【杀】",
  ["#rfenghou__siba_trigger"] = "四八",
  ["#rfenghou__zhuanhuan-ask"] = "转换：你可以弃置一张%arg牌令 %src 发动“四八”！",
  ["@rfenghou__zhuanhuan"] = "转换",
}

local yyuaN = General:new(extension, "rfenghou__yyuaN", "fuyao", 4)
local hujiao = fk.CreateTriggerSkill{
  name = "rfenghou__hujiao",
  anim_type = "control",
  events = {fk.PreCardUse, fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.PreCardUse then
        return (player.phase == Player.Play or table.contains(data.card.skillNames, self.name)) and data.tos
      elseif event == fk.EventPhaseStart then
        return player.phase == Player.Finish and
          table.find(player:getTableMark("@$rfenghou__hujiao"), function (name)
            local card = Fk:cloneCard(name)
            card.skillName = self.name
            return card.type ~= Card.TypeEquip and card.sub_type ~= Card.SubtypeDelayedTrick and
              player:canUse(card, {bypass_distances = true, bypass_times = true})
          end)
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.PreCardUse then
      if table.contains(data.card.skillNames, self.name) then
        return true
      else
        return player.room:askForSkillInvoke(player, self.name, nil, "#rfenghou__hujiao-invoke:::"..data.card:toLogString())
      end
    elseif event == fk.EventPhaseStart then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.PreCardUse then
      if player.phase == Player.Play then
        local mark = player:getTableMark("@$rfenghou__hujiao")
        table.insertIfNeed(mark, data.card.name)
        room:setPlayerMark(player, "@$rfenghou__hujiao", mark)
      end
      local targets = {}
      for _, orig_to in ipairs(data.tos) do
        for _, p in ipairs(room.alive_players) do
          if not player:isProhibited(p, data.card) and
          (data.card.sub_type == Card.SubtypeDelayedTrick or data.card.skill:modTargetFilter(p.id, {}, player, data.card, false)) then
            local ho_spair_check = true
            if #orig_to > 1 then
              --target_filter check, for collateral, diversion...
              local ho_spair_target = {p.id}
              for i = 2, #orig_to, 1 do
                local c_pid = orig_to[i]
                if not data.card.skill:modTargetFilter(c_pid, ho_spair_target, player, data.card, true) then
                  ho_spair_check = false
                  break
                end
                table.insert(ho_spair_target, c_pid)
              end
            end
            if ho_spair_check then
              table.insert(targets, p.id)
            end
          end
        end
      end
      if #targets > 0 then
        local random_target = table.random(targets)
        if #TargetGroup:getRealTargets(data.tos) == 1 then
          if #targets > 1 then
            for i = 1, 2, 1 do
              for _, p in ipairs(room:getAllPlayers()) do
                if table.contains(targets, p.id) then
                  room:setEmotion(p, "./image/anim/selectable")
                  room:notifyMoveFocus(p, self.name)
                  room:delay(300)
                end
              end
            end
            for _, p in ipairs(room:getAllPlayers()) do
              if table.contains(targets, p.id) then
                room:setEmotion(p, "./image/anim/selectable")
                room:delay(600)
                if p.id == random_target then
                  room:doIndicate(data.from, {random_target})
                  break
                end
              end
            end
          end
          data.tos[1][1] = random_target
        else
          local new_targets = table.random(targets, math.random(1, #TargetGroup:getRealTargets(data.tos)))
          for i = 1, #data.tos, 1 do
            if i <= #new_targets then
              data.tos[i][1] = new_targets[i]
            else
              data.tos[i] = nil
            end
          end
        end
      else
        data.tos = {}
      end
    elseif event == fk.EventPhaseStart then
      local all_names = table.simpleClone(player:getTableMark("@$rfenghou__hujiao"))
      local names, tmp = {}, {}
      for _, name in ipairs(all_names) do
        if not tmp[name] then
          table.insert(names, name)
          tmp[name] = true
        end
      end
      for _, name in ipairs(names) do
        if player.dead then return end
        local card = Fk:cloneCard(name)
        card.skillName = self.name
        if card.type ~= Card.TypeEquip and card.sub_type ~= Card.SubtypeDelayedTrick and
          player:canUse(card, {bypass_distances = true, bypass_times = true}) then
          if card.multiple_targets and card.skill.min_target_num == 0 then
            room:useCard{
              from = player.id,
              card = card,
              extraUse = true,
            }
          else
            room:useCard{
              from = player.id,
              tos = {{player:getNextAlive().id}},
              card = card,
              extraUse = true,
            }
          end
        end
      end
    end
  end,
}
yyuaN:addSkill(hujiao)
Fk:loadTranslationTable{
  ["rfenghou__yyuaN"] = "yyuaN低调的温柔胖宝宝",
  ["#rfenghou__yyuaN"] = "娇蛮小公主",
  ["designer:rfenghou__yyuaN"] = "zzcclll朱苦力",
  --["illustrator:rfenghou__yyuaN"] = "",

  ["rfenghou__hujiao"] = "胡搅",
  [":rfenghou__hujiao"] = "出牌阶段，你使用牌时，可令之随机指定目标。结束阶段，你依次视为使用本局你使用过的“胡搅”牌每牌名各一张，且均须触发“胡搅”。",
  ["#rfenghou__hujiao-invoke"] = "胡搅：是否令%arg随机指定目标？",
  ["@$rfenghou__hujiao"] = "胡搅",
}

local miaomiao = General:new(extension, "rfenghou__miaomiao", "fuyao", 4)
local juer = fk.CreateTriggerSkill{
  name = "rfenghou__juer",
  anim_type = "defensive",
  events = { fk.TargetConfirming, fk.BeforeCardsMove },
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    if event == fk.TargetConfirming then
      return (target == player or data.from == player.id) and
        (data.card.number == 2 or Fk:translate(data.card.trueName, "zh_CN"):len() == 2)
    elseif event == fk.BeforeCardsMove then
      local id = 0
      local source = player
      local card
      for _, move in ipairs(data) do
        if move.to == player.id and move.toArea == Card.PlayerJudge then
          for _, info in ipairs(move.moveInfo) do
            id = info.cardId
            if info.fromArea == Card.PlayerJudge then
              source = player.room:getPlayerById(move.from) or player
            else
              source = player
            end
            card = source:getVirualEquip(id)
            if not card then card = Fk:getCardById(id) end
            if card.sub_type == Card.SubtypeDelayedTrick and
              (card.number == 2 or Fk:translate(card.trueName, "zh_CN"):len() == 2) then
              return true
            end
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetConfirming then
      AimGroup:cancelTarget(data, target.id)
      return true
    elseif event == fk.BeforeCardsMove then
      local source = player
      local mirror_moves = {}
      local ids = {}
      for _, move in ipairs(data) do
        if move.to == player.id and move.toArea == Card.PlayerJudge then
          local move_info = {}
          local mirror_info = {}
          for _, info in ipairs(move.moveInfo) do
            local id = info.cardId
            if info.fromArea == Card.PlayerJudge then
              source = room:getPlayerById(move.from) or player
            else
              source = player
            end
            local card = source:getVirualEquip(id)
            if not card then card = Fk:getCardById(id) end
            if card.sub_type == Card.SubtypeDelayedTrick and
              (card.number == 2 or Fk:translate(card.trueName, "zh_CN"):len() == 2) then
              table.insert(mirror_info, info)
              table.insert(ids, id)
            else
              table.insert(move_info, info)
            end
          end
          if #mirror_info > 0 then
            move.moveInfo = move_info
            local mirror_move = table.clone(move)
            mirror_move.to = nil
            mirror_move.toArea = Card.DiscardPile
            mirror_move.moveInfo = mirror_info
            table.insert(mirror_moves, mirror_move)
          end
        end
      end
      table.insertTable(data, mirror_moves)
    end
  end
}
local aisui = fk.CreateTriggerSkill{
  name = "rfenghou__aisui",
  anim_type = "control",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart, fk.EventPhaseProceeding},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.EventPhaseStart then
        return player.phase == Player.Play
      elseif event == fk.EventPhaseProceeding then
        if player.phase == Player.Judge then
          return not player:isAllNude()
        elseif player.phase == Player.Draw then
          return #player:getCardIds("e") > 0 or
            table.find(player.room:getOtherPlayers(player), function (p)
              return not p:isNude()
            end)
        elseif player.phase == Player.Discard then
          return table.find(player.room.alive_players, function (p)
            return table.find(p:getCardIds("he"), function (id)
              return not player:prohibitDiscard(id)
            end)
          end)
        end
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local skills = {}
      for _, general in ipairs(Fk:getAllGenerals()) do
        for _, skill in ipairs(general.skills) do
          if not player:hasSkill(skill, true) and string.find(Fk:translate(":"..skill.name, "zh_CN"), "出牌阶段限一次") then
            table.insertIfNeed(skills, skill.name)
          end
        end
      end
      if #skills > 0 then
        local skill = table.random(skills)
        room:addTableMark(player, self.name, skill)
        room:handleAddLoseSkills(player, skill, nil, true, false)
      end
    elseif event == fk.EventPhaseProceeding then
      if player.phase == Player.Judge then
        room:recastCard(player:getCardIds("hej"), player, self.name)
        if not player.dead then
          local judge = {
            who = player,
            reason = "lightning",
            pattern = ".|2~9|spade",
          }
          room:judge(judge)
          if not player.dead and
            judge.card.suit == Card.Spade and judge.card.number > 1 and judge.card.number < 10 then
            room:damage{
              to = player,
              damage = 3,
              damageType = fk.ThunderDamage,
              skillName = self.name,
            }
          end
        end
        player._phase_end = true
      elseif player.phase == Player.Draw then
        local targets = {}
        if #player:getCardIds("e") > 0 then
          table.insert(targets, player.id)
        end
        for _, p in ipairs(room:getOtherPlayers(player)) do
          if not p:isNude() then
            table.insert(targets, p.id)
          end
        end
        targets = table.random(targets, math.random(1, #targets))
        local moves = {}
        for _, id in ipairs(targets) do
          local ids
          if id == player.id then
            ids = table.random(player:getCardIds("e"), 1)
          else
            ids = table.random(room:getPlayerById(id):getCardIds("he"), 1)
          end
          table.insert(moves, {
            from = id,
            to = player.id,
            ids = ids,
            toArea = Card.PlayerHand,
            moveReason = fk.ReasonPrey,
            skillName = self.name,
            proposer = player.id,
            moveVisible = false,
          })
        end
        if #moves > 0 then
          room:moveCards(table.unpack(moves))
          player._phase_end = true
        end
      elseif player.phase == Player.Discard then
        local targets = table.filter(room.alive_players, function (p)
          return table.find(p:getCardIds("he"), function (id)
            return not player:prohibitDiscard(id)
          end) ~= nil
        end)
        targets = table.random(targets, math.random(1, #targets))
        local moves = {}
        for _, p in ipairs(targets) do
          local ids
          if p == player.id then
            ids = table.random(table.filter(player:getCardIds("he"), function (id)
              return not player:prohibitDiscard(id)
            end), 1)
          else
            ids = table.random(p:getCardIds("he"), 1)
          end
          table.insert(moves, {
            from = p.id,
            ids = ids,
            toArea = Card.DiscardPile,
            moveReason = fk.ReasonDiscard,
            skillName = self.name,
            proposer = player.id,
            moveVisible = true,
          })
        end
        if #moves > 0 then
          room:moveCards(table.unpack(moves))
          player._phase_end = true
        end
      end
    end
  end,

  refresh_events = {fk.AfterSkillEffect},
  can_refresh = function (self, event, target, player, data)
    return target == player and table.contains(player:getTableMark(self.name), data.name)
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    room:removeTableMark(player, self.name, data.name)
    room:handleAddLoseSkills(player, "-"..data.name, nil, true, false)
  end,
}
miaomiao:addSkill(juer)
miaomiao:addSkill(aisui)
Fk:loadTranslationTable{
  ["rfenghou__miaomiao"] = "独孤妙妙",
  ["#rfenghou__miaomiao"] = "云月有归处",
  ["designer:rfenghou__miaomiao"] = "扬林",
  --["illustrator:rfenghou__miaomiao"] = "",
  ["cv:rfenghou__miaomiao"] = "lost＆刺刺背",

  ["rfenghou__juer"] = "拒贰",
  [":rfenghou__juer"] = "锁定技，你使用或被使用点数或牌名字数为2的牌时，取消之。",
  ["rfenghou__aisui"] = "爱随",
  [":rfenghou__aisui"] = "锁定技，判定阶段，你重铸区域内所有牌，执行一次【闪电】判定；出牌阶段，你随机获得一项“出牌阶段限一次”的技能，"..
  "且发动后失去之；摸牌/弃牌阶段，你改为随机获得/弃置任意名角色各一张牌。",

  ["$rfenghou__juer"] = "德莱尼拒绝了力量，真是愚蠢。",
  ["$rfenghou__aisui"] = "我的双刀，渴了！",
  ["~rfenghou__miaomiao"] = "饿饿！",
}

local pangpang = General:new(extension, "rfenghou__pangpang", "fuyao", 3)
Fk:loadTranslationTable{
  ["rfenghou__pangpang"] = "胖即是胖",
  ["#rfenghou__pangpang"] = "@全体成员",
  ["designer:rfenghou__pangpang"] = "屑",
  --["illustrator:rfenghou__pangpang"] = "",
}

local queyi = fk.CreateViewAsSkill{
  name = "rfenghou__queyi",
  pattern = ".",
  prompt = function (self, selected_cards, selected)
    local arg1, arg2 = "", ""
      if Fk:cloneCard(self.interaction.data).type == Card.TypeBasic then
        local suits = {1, 2, 3, 4}
        for _, id in ipairs(Fk:currentRoom():getBanner("@$CenterArea")) do
          table.removeOne(suits, Fk:getCardById(id).suit)
        end
        arg1 = U.ConvertSuit(suits[1], "int", "sym")
        arg2 = "basic"
      else
        local types = {1, 2, 3}
        for _, id in ipairs(Fk:currentRoom():getBanner("@$CenterArea")) do
          table.removeOne(types, Fk:getCardById(id).type)
        end
        local mapper = {"basic", "trick", "equip"}
        arg1 = mapper[types[1]]
        arg2 = "trick"
      end
    return "#rfenghou__queyi:::"..arg1..":"..arg2
  end,
  interaction = function(self)
    local all_names = {}
    local suits, types = {}, {}
    for _, id in ipairs(Fk:currentRoom():getBanner("@$CenterArea")) do
      table.insertIfNeed(suits, Fk:getCardById(id).suit)
      table.insertIfNeed(types, Fk:getCardById(id).type)
    end
    table.removeOne(suits, Card.NoSuit)
    if #suits == 3 and #types == 2 then
      all_names = U.getAllCardNames("bt")
    elseif #suits == 3 then
      all_names = U.getAllCardNames("b")
    elseif #types == 2 then
      all_names = U.getAllCardNames("t")
    end
    return U.CardNameBox {
      choices = U.getViewAsCardNames(Self, self.name, all_names),
      all_choices = all_names,
    }
  end,
  card_filter = function(self, to_select, selected)
    if #selected == 0 and Fk.all_card_types[self.interaction.data] ~= nil then
      if Fk:cloneCard(self.interaction.data).type == Card.TypeBasic then
        local suits = {1, 2, 3, 4}
        for _, id in ipairs(Fk:currentRoom():getBanner("@$CenterArea")) do
          table.removeOne(suits, Fk:getCardById(id).suit)
        end
        return Fk:getCardById(to_select).suit == suits[1]
      else
        local types = {1, 2, 3}
        for _, id in ipairs(Fk:currentRoom():getBanner("@$CenterArea")) do
          table.removeOne(types, Fk:getCardById(id).type)
        end
        return Fk:getCardById(to_select).type == types[1]
      end
    end
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or Fk.all_card_types[self.interaction.data] == nil then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcard(cards[1])
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function (self, player)
    local suits, types = {}, {}
    for _, id in ipairs(Fk:currentRoom():getBanner("@$CenterArea")) do
      table.insertIfNeed(suits, Fk:getCardById(id).suit)
      table.insertIfNeed(types, Fk:getCardById(id).type)
    end
    table.removeOne(suits, Card.NoSuit)
    return #suits == 3 or #types == 2
  end,
  enabled_at_response = function (self, player, response)
    if response or player:isNude() then return end
    local suits, types = {}, {}
    for _, id in ipairs(Fk:currentRoom():getBanner("@$CenterArea")) do
      table.insertIfNeed(suits, Fk:getCardById(id).suit)
      table.insertIfNeed(types, Fk:getCardById(id).type)
    end
    table.removeOne(suits, Card.NoSuit)
    local all_names = {}
    if #suits == 3 and #types == 2 then
      all_names = U.getAllCardNames("bt")
    elseif #suits == 3 then
      all_names = U.getAllCardNames("b")
    elseif #types == 2 then
      all_names = U.getAllCardNames("t")
    end
    for _, name in ipairs(all_names) do
      local card = Fk:cloneCard(name)
      card.skillName = self.name
      if #suits == 3 then
        card.suit = suits[1]
      end
      if (Fk.currentResponsePattern == nil and player:canUse(card)) or
        (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card)) then
        return true
      end
    end
  end,
}
local atgroup = fk.CreateActiveSkill{
  name = "rfenghou__atgroup",
  anim_type = "control",
  card_num = 0,
  target_num = 0,
  prompt = "#rfenghou__atgroup",
  can_use = function(self, player)
    if player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and
      table.find(Fk:currentRoom().alive_players, function (p)
        if table.find(p:getCardIds("he"), function (id)
          return not Self:prohibitDiscard(id)
        end) then
          return true
        end
      end) then
      return true
    end
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local targets, n = {}, 0
    for _, p in ipairs(room:getAlivePlayers()) do
      if player.dead then return end
      local card
      if p == player then
        card = room:askForDiscard(player, 1, 1, true, self.name, false, nil, "#rfenghou__atgroup-discard::"..player.id)
        if #card > 0 then
          n = n + 1
          if Fk:getCardById(card[1]).type == Card.TypeEquip then
            table.insert(targets, player)
          end
        end
      elseif not p:isNude() then
        card = room:askForCardChosen(player, p, "he", self.name, "#rfenghou__atgroup-discard::"..p.id)
        n = n + 1
        if card and Fk:getCardById(card).type == Card.TypeEquip then
          table.insert(targets, p)
        end
        room:throwCard(card, self.name, p, player)
      end
    end
    n = math.min(#room:getBanner("@$CenterArea"), n)
    if player.dead or n == 0 then return end
    local result = room:askForArrangeCards(player, self.name,
    {
      {}, room:getBanner("@$CenterArea"),
      "Top", "$CenterArea",
    }, "#rfenghou__atgroup-put:::"..n, true, #room:getBanner("@$CenterArea"), {n, 999})
    if #result[1] > 0 then
      result[1] = table.reverse(result[1])
      room:moveCards({
        ids = result[1],
        fromArea = Card.DiscardPile,
        toArea = Card.DrawPile,
        moveReason = fk.ReasonPut,
        skillName = self.name,
        moveVisible = true,
        drawPilePosition = 1,
      })
    end
    if player.dead then return end
    local card = Fk:cloneCard("amazing_grace")
    card.skillName = self.name
    if not player:canUse(card) then return end
    if #targets > 0 and room:askForSkillInvoke(player, self.name, nil, "#rfenghou__atgroup-cancel") then
      local tos = {}
      for _, p in ipairs(room:getAlivePlayers()) do
        if not table.contains(targets, p) and player:canUseTo(card, p) then
          table.insert(tos, {p.id})
        end
      end
      if #tos > 0 then
        room:useCard{
          from = player.id,
          tos = tos,
          card = card,
        }
      end
    else
      room:useCard{
        from = player.id,
        card = card,
      }
    end
  end,
}
queyi.CenterArea = true
atgroup.CenterArea = true
pangpang:addSkill(queyi)
pangpang:addSkill(atgroup)
Fk:loadTranslationTable{
  ["rfenghou__queyi"] = "缺1",
  [":rfenghou__queyi"] = "若中央区仅缺少一种花色/类型的牌，你可以将一张此花色/类型的牌当任意基本/普通锦囊牌使用。",
  ["rfenghou__atgroup"] = "@全体成员",
  [":rfenghou__atgroup"] = "出牌阶段限一次，你可以弃置所有角色各一张牌，然后将中央区至多等量张牌置于牌堆顶，视为使用一张【五谷丰登】，"..
  "且可令弃置装备牌的角色不成为目标。",
  ["#rfenghou__queyi"] = "缺1：你可以将一张%arg当任意%arg2使用",
  ["#rfenghou__atgroup"] = "@全体成员：弃置所有角色各一张牌，然后将中央区的牌置于牌堆顶，视为使用【五谷丰登】",
  ["#rfenghou__atgroup-discard"] = "@全体成员：弃置 %dest 一张牌",
  ["#rfenghou__atgroup-put"] = "@全体成员：将中央区至多%arg张牌置于牌堆顶",
  ["#rfenghou__atgroup-cancel"] = "@全体成员：是否令弃置装备牌的角色不成为目标？",
}

local yanglin = General:new(extension, "rfenghou__yanglin", "fuyao", 4)
local shanebao = fk.CreateTriggerSkill{
  name = "rfenghou__shanebao",
  mute = true,
  frequency = Skill.Compulsory,
  events = {--fk.AfterCardsMove, 
  fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      local turn_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Turn)
      if turn_event == nil then return end
      --[[if event == fk.AfterCardsMove then
        if #player.room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
          if e.id ~= player.room.logic:getCurrentEvent().id then
            for _, move in ipairs(e.data) do
              if move.from then
                for _, info in ipairs(move.moveInfo) do
                  if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                    return true
                  end
                end
              end
            end
          end
        end, Player.HistoryTurn) == 0 then return end
        for _, move in ipairs(data) do
          if move.to == player.id and move.moveReason == fk.ReasonDraw and move.skillName ~= self.name then
            return true
          end
          if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.skillName ~= self.name and
            move.proposer == player.id and not player:isNude() then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                return true
              end
            end
          end
        end
      else]]--
      if event == fk.AfterCardTargetDeclared and data.card.trueName == "slash" then
        if #player.room.logic:getEventsOfScope(GameEvent.Recover, 1, Util.TrueFunc, Player.HistoryTurn) == 0 then return end
        if #player.room:getUseExtraTargets(data) == 0 then return end
        return target == player or table.contains(TargetGroup:getRealTargets(data.tos), player.id)
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    --[[if event == fk.AfterCardsMove then
      local targets = {}
      room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
        for _, move in ipairs(e.data) do
          if move.from then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                table.insertIfNeed(targets, move.from)
              end
            end
          end
        end
      end, Player.HistoryTurn)
      local n = #targets
      local yes1, yes2 = false, false
      for _, move in ipairs(data) do
        if move.to == player.id and move.moveReason == fk.ReasonDraw and move.skillName ~= self.name then
          yes1 = true
        end
        if not player:hasSkill(self) then return end
        if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.skillName ~= self.name and
          move.proposer == player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
              yes2 = true
              break
            end
          end
        end
      end
      if yes1 then
        room:notifySkillInvoked(player, self.name, "drawcard")
        player:drawCards(n, self.name)
      end
      if not player:hasSkill(self) then return end
      if yes2 and not player:isNude() then
        room:notifySkillInvoked(player, self.name, "negative")
        room:askForDiscard(player, n, n, true, self.name, false)
      end
    else]]--
    if event == fk.AfterCardTargetDeclared then
      local targets = {}
      room.logic:getEventsOfScope(GameEvent.Recover, 1, function(e)
        local recover = e.data[1]
        table.insertIfNeed(targets, recover.who.id)
      end, Player.HistoryTurn)
      local n = #targets
      targets = room:getUseExtraTargets(data)
      local tos = room:askForChoosePlayers(target, targets, 1, n,
        "#rfenghou__shanebao-choose:::"..data.card:toLogString()..":"..n, self.name, true)
      if #tos > 0 then
        for _, id in ipairs(tos) do
          table.insert(data.tos, {id})
        end
      end
    end
  end,
}
local beihuanqu = fk.CreateTriggerSkill{
  name = "rfenghou__beihuanqu",
  anim_type = "control",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if player.phase == Player.Start then
        return true
      elseif player.phase == Player.Finish then
        return #player:getTableMark("rfenghou__beihuanqu-turn") > 0 or
          #player.room.logic:getEventsOfScope(GameEvent.Dying, 1, Util.TrueFunc, Player.HistoryTurn) > 0
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if player.phase == Player.Start then
      room:doIndicate(player.id, table.map(room.alive_players, Util.IdMapper))
      for _, p in ipairs(room:getAlivePlayers()) do
        if not p.dead then
          local success, dat = room:askForUseActiveSkill(p, "rfenghou__beihuanqu_active",
            "#rfenghou__beihuanqu-choice", true, nil, false)
          if success and dat then
            if #dat.cards > 0 then
              room:throwCard(dat.cards, self.name, p, p)
            elseif #dat.targets > 0 then
              local to = room:getPlayerById(dat.targets[1])
              room:recover{
                who = to,
                num = 1,
                recoverBy = p,
                skillName = self.name,
              }
              if p:isWounded() and not p.dead then
                room:recover{
                  who = p,
                  num = 1,
                  recoverBy = p,
                  skillName = self.name,
                }
              end
            end
          else
            room:loseHp(p, 1, self.name)
          end
        end
      end
    elseif player.phase == Player.Finish then
      local targets = table.simpleClone(player:getTableMark("rfenghou__beihuanqu-turn"))
      room.logic:getEventsOfScope(GameEvent.Dying, 1, function(e)
        table.insertIfNeed(targets, e.data[1].who)
      end, Player.HistoryTurn)
      player:drawCards(#targets, self.name)
    end
  end,

  refresh_events = {fk.HpRecover},
  can_refresh = function (self, event, target, player, data)
    if not target:isWounded() then
      local turn_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Turn)
      return turn_event and turn_event.data[1] == player
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local mark = player:getTableMark("rfenghou__beihuanqu-turn")
    table.insertIfNeed(mark, target.id)
    player.room:setPlayerMark(player, "rfenghou__beihuanqu-turn", mark)
  end,
}
local beihuanqu_active = fk.CreateActiveSkill{
  name = "rfenghou__beihuanqu_active",
  min_card_num = 0,
  max_card_num = 2,
  min_target_num = 0,
  max_target_num = 1,
  card_filter = function (self, to_select, selected)
    return #selected < 2 and table.contains(Self:getCardIds("h"), to_select) and not Self:prohibitDiscard(to_select)
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected_cards == 0 and #selected == 0 and to_select ~= Self.id and
      Fk:currentRoom():getPlayerById(to_select):isWounded()
  end,
  feasible = function (self, selected, selected_cards)
    return (#selected_cards == 2 and #selected == 0) or (#selected_cards == 0 and #selected == 1)
  end,
}
Fk:addSkill(beihuanqu_active)
yanglin:addSkill(shanebao)
yanglin:addSkill(beihuanqu)
Fk:loadTranslationTable{
  ["rfenghou__yanglin"] = "扬林",
  ["#rfenghou__yanglin"] = "星の缘",
  ["designer:rfenghou__yanglin"] = "志文",
  --["illustrator:rfenghou__yanglin"] = "",

  ["rfenghou__shanebao"] = "善恶报",
  [":rfenghou__shanebao"] = "锁定技，你使用或被使用【杀】时，使用【杀】的角色能指定至多X名角色为额外目标（X为此回合回复体力的角色数）。",
  ["rfenghou__beihuanqu"] = "悲欢曲",
  [":rfenghou__beihuanqu"] = "锁定技，准备阶段，所有角色依次选择：失去1点体力；弃置两张手牌；和另一名已受伤的角色各回复1点体力。"..
  "结束阶段，你摸Y张牌（Y为此回合进入濒死和回满体力的角色数之和）。",
  ["#rfenghou__shanebao-choose"] = "善恶报：你可以为此%arg额外指定至多%arg2个目标",
  ["rfenghou__beihuanqu_active"] = "悲欢曲",
  ["#rfenghou__beihuanqu-choice"] = "点“取消”失去1点体力；<br>选择两张手牌弃置；<br>"..
  "选择另一名已受伤角色，你与其各回复1点体力",
}

local toufa = General:new(extension, "rfenghou__toufa", "fuyao", 4)
local canxi = fk.CreateTriggerSkill{
  name = "rfenghou__canxi",
  frequency = Skill.Compulsory,
  events = {fk.DamageCaused, fk.HpRecover, fk.TargetConfirmed, fk.GameStart, fk.RoundStart},
  mute = true,
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.DamageCaused then
      return target and player:getMark("@rfenghou__canxi1-round") == target.kingdom and
        not table.contains(player:getTableMark("rfenghou__canxi1-turn"), target.id)
    elseif event == fk.HpRecover then
      return player:getMark("@rfenghou__canxi2-round") == target.kingdom and
      not target.dead and target ~= player and not table.contains(player:getTableMark("rfenghou__canxi21-turn"), target.id)
    elseif event == fk.TargetConfirmed then
      if player == target and data.from ~= player.id then
        local p = player.room:getPlayerById(data.from)
        return player:getMark("@rfenghou__canxi2-round") == p.kingdom and
          not table.contains(player:getTableMark("rfenghou__canxi22-turn"), p.id)
      end
    elseif event == fk.RoundStart then
      return #player:getTableMark("@rfenghou__canxi_exist_kingdoms") > 0
    elseif event == fk.GameStart then
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if event == fk.DamageCaused then
      room:notifySkillInvoked(player, self.name, "offensive")
      local mark = player:getTableMark("rfenghou__canxi1-turn")
      table.insert(mark, target.id)
      room:setPlayerMark(player, "rfenghou__canxi1-turn", mark)
      data.damage = data.damage + 1
    elseif event == fk.HpRecover then
      room:notifySkillInvoked(player, self.name, "control")
      local mark = player:getTableMark("rfenghou__canxi21-turn")
      table.insert(mark, target.id)
      room:setPlayerMark(player, "rfenghou__canxi21-turn", mark)
      room:loseHp(target, 1, self.name)
    elseif event == fk.TargetConfirmed then
      room:notifySkillInvoked(player, self.name, "defensive")
      local mark = player:getTableMark("rfenghou__canxi22-turn")
      table.insert(mark, data.from)
      room:setPlayerMark(player, "rfenghou__canxi22-turn", mark)
      table.insertIfNeed(data.nullifiedTargets, player.id)
    elseif event == fk.RoundStart then
      room:notifySkillInvoked(player, self.name, "special")
      local choice1 = room:askForChoice(player, player:getMark("@rfenghou__canxi_exist_kingdoms"), self.name, "#rfenghou__canxi-choice1")
      local choice2 = room:askForChoice(player, {"rfenghou__canxi1", "rfenghou__canxi2"}, self.name,
        "#rfenghou__canxi-choice2:::"..choice1, true)
      room:setPlayerMark(player, "@"..choice2.."-round", choice1)
    elseif event == fk.GameStart then
      room:notifySkillInvoked(player, self.name, "special")
      local kingdoms = {}
      for _, p in ipairs(room.alive_players) do
        table.insertIfNeed(kingdoms, p.kingdom)
      end
      room:setPlayerMark(player, "@rfenghou__canxi_exist_kingdoms", kingdoms)
      if #kingdoms < #Fk:getKingdomMap("god") then  --youmu智慧最有用的一集
        room:changeMaxHp(player, #Fk:getKingdomMap("god") - #kingdoms)
      end
    end
  end,

  on_lose = function (self, player, is_death)
    local room = player.room
    room:setPlayerMark(player, "@rfenghou__canxi_exist_kingdoms", 0)
    room:setPlayerMark(player, "@rfenghou__canxi1-round", 0)
    room:setPlayerMark(player, "@rfenghou__canxi2-round", 0)
  end,
}
local canxi_distance = fk.CreateDistanceSkill{
  name = "#rfenghou__canxi_distance",
  frequency = Skill.Compulsory,
  correct_func = function(self, from, to)
    return -#table.filter(Fk:currentRoom().alive_players, function (p)
      return p:hasSkill(canxi) and p:getMark("@rfenghou__canxi1-round") == from.kingdom
    end)
  end,
}
local pizhi = fk.CreateTriggerSkill{
  name = "rfenghou__pizhi",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseEnd, fk.Death},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.EventPhaseEnd then
        return target == player and player.phase == Player.Finish and player:getMark("rfenghou__canxi_removed_kingdoms") > 0
      elseif event == fk.Death then
        return player:getMark("@rfenghou__canxi1-round") == target.kingdom or
          player:getMark("@rfenghou__canxi2-round") == target.kingdom or
          (not table.find(player.room.alive_players, function(p)
            return p.kingdom == target.kingdom
          end) and table.contains(player:getTableMark("@rfenghou__canxi_exist_kingdoms"), target.kingdom))
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.Death then
      if player:getMark("@rfenghou__canxi1-round") == target.kingdom then
        room:setPlayerMark(player, "@rfenghou__canxi1-round", 0)
      end
      if player:getMark("@rfenghou__canxi2-round") == target.kingdom then
        room:setPlayerMark(player, "@rfenghou__canxi2-round", 0)
      end
      local mark = player:getMark("@rfenghou__canxi_exist_kingdoms")
      if table.removeOne(mark, target.kingdom) then
        room:setPlayerMark(player, "@rfenghou__canxi_exist_kingdoms", #mark > 0 and mark or 0)
        room:addPlayerMark(player, "rfenghou__canxi_removed_kingdoms")
      end
      player:drawCards(player:getMark("rfenghou__canxi_removed_kingdoms"), self.name)
      if not player.dead and player:isWounded() then
        room:recover({
          who = player,
          num = 1,
          recoverBy = player,
          skillName = self.name
        })
      end
    else
      player:drawCards(player:getMark("rfenghou__canxi_removed_kingdoms"), self.name)
    end
  end,
}
local zhonggu = fk.CreateTriggerSkill{
  name = "rfenghou__zhonggu$",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.DrawNCards},
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    local n = #table.filter(room.alive_players, function(p)
      return Fk.generals[p.general].package.extensionName == "hanqing"
    end)
    if room:getBanner("RoundCount") >= n then
      room:notifySkillInvoked(player, self.name, "drawcard")
      data.n = data.n + 2
    else
      room:notifySkillInvoked(player, self.name, "negative")
      data.n = data.n - 1
    end
  end,
}
canxi:addRelatedSkill(canxi_distance)
toufa:addSkill(canxi)
toufa:addSkill(pizhi)
toufa:addSkill(zhonggu)
Fk:loadTranslationTable{
  ["rfenghou__toufa"] = "头发好借好还",
  ["#rfenghou__toufa"] = "头发好借好还",
  ["designer:rfenghou__toufa"] = "头发好借好还",
  --["illustrator:rfenghou__toufa"] = "",

  ["rfenghou__canxi"] = "残玺",
  [":rfenghou__canxi"] = "锁定技，游戏开始时，你获得场上各势力的“玺角”标记（每少一个“玺角”便加1点体力上限）。每轮开始时，"..
  "你选择一个“玺角”并选择一个效果生效直到下轮开始<br>「妄生」：该势力角色每回合首次造成伤害+1，计算与其他角色距离-1；<br>"..
  "「向死」：该势力其他角色每回合首次回复体力后失去1点体力，每回合对你使用的第一张牌无效。",
  ["rfenghou__pizhi"] = "圮秩",
  [":rfenghou__pizhi"] = "锁定技，结束阶段，你摸X张牌；有角色死亡时，若其势力与当前生效的“玺角”势力相同或是该势力最后一名角色，你失去此“玺角”，"..
  "然后摸X张牌并回复1点体力（X为你已失去的“玺角”数）。",
  ["rfenghou__zhonggu"] = "冢骨",
  [":rfenghou__zhonggu"] = "主公技，锁定技，游戏轮数大于等于汗青角色数时，你摸牌阶段摸牌数+2，反之-1。",

  ["@rfenghou__canxi_exist_kingdoms"] = "",
  ["#rfenghou__canxi-choice1"] = "残玺：选择本轮生效的“玺角”势力",
  ["#rfenghou__canxi-choice2"] = "残玺：选择本轮对 %arg 势力角色生效的效果",
  ["rfenghou__canxi1"] = "「妄生」",
  [":rfenghou__canxi1"] = "每回合首次造成伤害+1，计算与其他角色距离-1",
  ["@rfenghou__canxi1-round"] = "「妄生」",
  ["rfenghou__canxi2"] = "「向死」",
  [":rfenghou__canxi2"] = "每回合首次回复体力后失去1点体力，每回合对你使用的第一张牌无效",
  ["@rfenghou__canxi2-round"] = "「向死」",
}

local xie = General:new(extension, "rfenghou__xie", "fuyao", 3)


-- 好无语，本体里面的写错了
---@param card Card
local getFixedTargets = function (card, player)
  if card.skill:getMinTargetNum() == 0 then
    if card.multiple_targets then
      return table.map(table.filter(Fk:currentRoom().alive_players, function (p)
        return card.skill:modTargetFilter(p.id, {}, player, card)
      end), Util.IdMapper)
    else
      return {player.id}
    end
  end
  return {}
end
local jieshihuanhun = fk.CreateActiveSkill{
  name = "rfenghou__jieshihuanhun",
  anim_type = "offensive",
  card_num = 2,
  interaction = function(self, player)
    local all_names = table.filter(U.getAllCardNames("bt"), function (name)
      return player:canUse(Fk:cloneCard(name))
    end)
    return U.CardNameBox {
      choices = U.getViewAsCardNames(player, self.name, all_names),
      all_choices = all_names,
    }
  end,
  prompt = function (self, selected_cards, selected)
    if Self:getMark(self.name) == 0 then
      return "#rfenghou__jieshihuanhun0"
    else
      local names = Self:getMark(self.name)[1]
      if #names == 1 then
      return "#rfenghou__jieshihuanhun1:::"..names[1]
      elseif #names == 2 then
      return "#rfenghou__jieshihuanhun2:::"..names[1]..":"..names[2]
      end
    end
    return ""
  end,
  target_tip = function (self, to_select, selected, selected_cards, card, selectable, extra_data)
    if Self:getMark("rfenghou__jieshihuanhun") ~= 0 then
      if table.contains(Self:getMark("rfenghou__jieshihuanhun")[2], to_select) then
        return "rfenghou__jieshihuanhun_tip"
      end
    end
  end,
  card_filter = function(self, to_select, selected, player)
    if #selected == 0 then return true end
    if #selected == 1 then
      if player:getMark(self.name) ~= 0 then
        local names = player:getMark(self.name)[1]
        return table.contains(names, Fk:getCardById(to_select).trueName)
        or table.contains(names, Fk:getCardById(selected[1]).trueName)
      end
      return true
    end
  end,
  target_filter = function(self, to_select, selected, cards, _, _, player)
    if self.interaction.data == nil or #cards ~= 2 then return false end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcards(cards)
    if card:getFixedTargets(player) then return false end
    return card.skill:targetFilter(to_select, selected, cards, card, nil, player)
  end,
  feasible = function(self, selected, cards, player)
    if self.interaction.data == nil or #cards ~= 2 then return false end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(cards)
    local mark = player:getMark(self.name)
    if mark ~= 0 then
      local tos = table.simpleClone(card.skill:getMinTargetNum() == 0 and getFixedTargets(card, player) or selected)
      if card.skill:getMinTargetNum() == 2 then tos = {tos[1]} end
      if table.every(tos, function (id) return table.contains(mark[2], id) end) then
        return false
      end
    end
    return card.skill:feasible(selected, cards, player, card)
  end,
  can_use = function(self, player)
    return not player:isNude()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(effect.cards)
    local tos = card.skill:getMinTargetNum() == 0 and getFixedTargets(card, player) or effect.tos
    local record_tos = table.simpleClone(tos)
    if card.skill:getMinTargetNum() == 2 then
      record_tos = {record_tos[1]}
    end
    local names = {}
    for _, id in ipairs(card.subcards) do
      table.insertIfNeed(names, Fk:getCardById(id).trueName)
    end
    room:setPlayerMark(player, self.name, {names, record_tos})
    room:useCard{
      from = player.id,
      tos = table.map(tos, function(p) return {p} end),
      card = card,
      extraUse = true,
    }
  end,
}
xie:addSkill(jieshihuanhun)

local shengshengbuxi = fk.CreateTriggerSkill{
  name = "rfenghou__shengshengbuxi",
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player:getHandcardNum() == 1 then
      for _, move in ipairs(data) do
        if move.to == player.id and move.toArea == Player.Hand then return true end
        if move.from == player.id and table.find(move.moveInfo, function(info) return info.fromArea == Player.Hand end) then
          return true
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:setCardMark(Fk:getCardById(player.player_cards[Player.Hand][1]), "@@rfenghou_appease", 1)
  end,

  on_lose = function (self, player, is_death)
    for _, id in ipairs(player:getCardIds("h")) do
      if Fk:getCardById(id):getMark("@@rfenghou_appease") ~= 0 then
        player.room:setCardMark(Fk:getCardById(id), "@@rfenghou_appease", 0)
      end
    end
  end,
}

local shengshengbuxi2 = fk.CreateTriggerSkill{
  name = "#rfenghou__shengshengbuxi2",
  mute = true,
  priority = 0.99,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if not player.dead then
      for _, move in ipairs(data) do
        if move.from == player.id and move.extra_data and move.extra_data.shengshengbuxiCheck then
          return true
        end
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local _, dat = room:askForUseActiveSkill(player, "rfenghou__huaiyuan_active", "#rfenghou__huaiyuan-invoke", false)
    local to = dat and room:getPlayerById(dat.targets[1]) or player
    local choice = dat and dat.interaction or "draw1"
    if choice == "draw1" then
      to:drawCards(1, "huaiyuan")
    else
      room:addPlayerMark(to, "@"..choice, 1)
    end
  end,

  refresh_events = {fk.AfterCardsMove},
  can_refresh = Util.TrueFunc,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if Fk:getCardById(info.cardId):getMark("@@rfenghou_appease") ~= 0 then
            room:setCardMark(Fk:getCardById(info.cardId), "@@rfenghou_appease", 0)
            move.extra_data = move.extra_data or {}
            move.extra_data.shengshengbuxiCheck = true
          end
        end
      end
      if move.to == player.id and player:getHandcardNum() > 1 then
        for _, id in ipairs(player:getCardIds("h")) do
          if Fk:getCardById(id):getMark("@@rfenghou_appease") ~= 0 then
            player.room:setCardMark(Fk:getCardById(id), "@@rfenghou_appease", 0)
          end
        end
      end
    end
  end,
}
shengshengbuxi:addRelatedSkill(shengshengbuxi2)

local huaiyuan_attackrange = fk.CreateAttackRangeSkill{
  name = "#rfenghou__huaiyuan_attackrange",
  correct_func = function (self, from, to)
    return from:getMark("@rfenghou__huaiyuan_attackrange")
  end,
}
shengshengbuxi:addRelatedSkill(huaiyuan_attackrange)

local huaiyuan_maxcards = fk.CreateMaxCardsSkill{
  name = "#rfenghou__huaiyuan_maxcards",
  correct_func = function(self, player)
    return player:getMark("@rfenghou__huaiyuan_maxcards")
  end,
}
shengshengbuxi:addRelatedSkill(huaiyuan_maxcards)

local huaiyuan_active = fk.CreateActiveSkill{
  name = "rfenghou__huaiyuan_active",
  interaction = function()
    return UI.ComboBox {choices = {"draw1", "rfenghou__huaiyuan_maxcards", "rfenghou__huaiyuan_attackrange"}}
  end,
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_num = 1,
  target_filter = function(self, to_select, selected)
    return #selected == 0
  end,
}
Fk:addSkill(huaiyuan_active)

-- 解除OL依赖
Fk:loadTranslationTable{
  ["rfenghou__huaiyuan_active"] = "怀远",
  ["#rfenghou__huaiyuan-invoke"] = "怀远：令一名角色手牌上限+1 / 攻击范围+1 / 摸一张牌",
  ["rfenghou__huaiyuan_maxcards"] = "手牌上限+1",
  ["rfenghou__huaiyuan_attackrange"] = "攻击范围+1",
  ["@rfenghou__huaiyuan_maxcards"] = "怀远:上限+",
  ["@rfenghou__huaiyuan_attackrange"] = "怀远:范围+",
}

xie:addSkill(shengshengbuxi)

Fk:loadTranslationTable{
  ["rfenghou__xie"] = "屑",
  ["#rfenghou__xie"] = "",
  ["designer:rfenghou__xie"] = "花生",
  --["illustrator:rfenghou__xie"] = "",

  ["rfenghou__jieshihuanhun"] = "借尸还魂",
  [":rfenghou__jieshihuanhun"] = "出牌阶段，你可以将两张牌当一张基本牌或普通锦囊牌使用，但需满足：<br>"..
  "1.至少有一张牌与你上次的转化底牌牌名相同；<br>2.至少有一个目标与你上次以此使用牌时不同。",
  ["#rfenghou__jieshihuanhun0"] = "借尸还魂：将两张牌当基本牌或普通锦囊牌使用",
  ["#rfenghou__jieshihuanhun1"] = "借尸还魂：将两张牌当基本牌或普通锦囊牌使用（必须包含【%arg】）<br>若目标只包含上次目标则失效！",
  ["#rfenghou__jieshihuanhun2"] = "借尸还魂：将两张牌当基本牌或普通锦囊牌使用（必须包含【%arg】或【%arg2】）<br>若目标只包含上次目标则失效！",
  ["rfenghou__jieshihuanhun_tip"] = "上次目标",

  ["rfenghou__shengshengbuxi"] = "生生不息",
  [":rfenghou__shengshengbuxi"] = "锁定技，你最后一张手牌具有“绥”标记。",
  ["@@rfenghou_appease"] = "绥",
}

local ralph = General:new(extension, "rfenghou__th_kogasa", "fuyao", 3, 3, General.Female)
local baogan = fk.CreateTriggerSkill{
  name = "rfenghou__baogan",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if player:getMark(self.name) < 11 and
      player:usedSkillTimes(self.name, Player.HistoryTurn) > 1 and
      #room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
        return e.data[1].from == player.id
      end, Player.HistoryPhase) == 0 then
        room:notifySkillInvoked(player, self.name, "negative")
      room:addPlayerMark(player, self.name, 1)
      room:endTurn()
    elseif math.random() < 1 - 0.1 * player:getMark(self.name) then
      room:notifySkillInvoked(player, self.name, "support")
      player:gainAnExtraPhase(Player.Play, true)
    end
  end,
}
local zhuanmi = fk.CreateActiveSkill{
  name = "rfenghou__zhuanmi",
  anim_type = "drawcard",
  prompt = function (self, selected_cards, selected_targets)
    return "#rfenghou__zhuanmi:::"..Self:getMark("rfenghou__zhuanmi-turn")
  end,
  card_num = function ()
    return Self:getMark("rfenghou__zhuanmi-turn")
  end,
  target_num = 0,
  expand_pile = function (self)
    return Fk:currentRoom():getBanner("@$CenterArea")
  end,
  can_use = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and
      player:getMark("rfenghou__zhuanmi-turn") > 0 and
      #Fk:currentRoom():getBanner("@$CenterArea") >= player:getMark("rfenghou__zhuanmi-turn")
  end,
  card_filter = function (self, to_select, selected)
    return #selected < Self:getMark("rfenghou__zhuanmi-turn") and table.contains(Fk:currentRoom():getBanner("@$CenterArea"), to_select)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    DIY.RemoveCenterCards(player, effect.cards)
    if #room:getBanner("@$CenterArea") == 0 and not player.dead then
      player:drawCards(#effect.cards, self.name)
    end
  end,
}
local zhuanmi_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou__zhuanmi_trigger",

  refresh_events = {fk.StartPlayCard},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(zhuanmi, true)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local n = #room.logic:getEventsOfScope(GameEvent.Phase, 999, function(e)
      return e.data[1] == player and e.data[2] == Player.Play
    end, Player.HistoryTurn)
    room:setPlayerMark(player, "rfenghou__zhuanmi-turn", n)
  end,
}
zhuanmi:addRelatedSkill(zhuanmi_trigger)
zhuanmi.CenterArea = true
ralph:addSkill(baogan)
ralph:addSkill(zhuanmi)
Fk:loadTranslationTable{
  ["rfenghou__th_kogasa"] = "‮ɥdןɐɹ‬",
  ["#rfenghou__th_kogasa"] = "",
  ["designer:rfenghou__th_kogasa"] = "易大剧",
  --["illustrator:rfenghou__th_kogasa"] = "",

  ["rfenghou__baogan"] = "爆肝",
  [":rfenghou__baogan"] = "锁定技，你有100%的概率能在出牌阶段结束后执行一个额外出牌阶段。若你在一个额外出牌阶段未能使用牌，则结束回合，"..
  "且概率永久降低10%。",
  ["rfenghou__zhuanmi"] = "赚米",
  [":rfenghou__zhuanmi"] = "出牌阶段限一次，你可以移去中央区的X张牌。若中央区因此清空，你摸X张牌（X为你本回合执行的出牌阶段数）。",
  ["#rfenghou__zhuanmi"] = "赚米：移去中央区的%arg张牌，若清空中央区则摸等量牌",
}

local emo = General:new(extension, "rfenghou__n_emoprincess", "fuyao", 4, 4, General.Female)
local zhufa = fk.CreateTriggerSkill{
  name = "rfenghou__zhufa",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      local room = player.room
      local cards = {}
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile then
          for _, info in ipairs(move.moveInfo) do
            local card = Fk:getCardById(info.cardId, true)
            if card.name ~= "charm" and card.is_damage_card and table.contains(room.discard_pile, info.cardId) then
              table.insertIfNeed(cards, info.cardId)
            end
          end
        end
      end
      cards = U.moveCardsHoldingAreaCheck(room, cards)
      if #cards > 0 then
        self.cost_data = {cards = cards}
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local ids = table.simpleClone(self.cost_data.cards)
    room:moveCardTo(ids, Card.Void, nil, fk.ReasonJustMove, self.name, nil, true, player.id)
    if Fk.all_card_types["charm"] == nil then return end
    for _, id in ipairs(ids) do
      if not table.find(Fk.cards, function (card)
        return card.trueName == Fk:getCardById(id).trueName and
        room:getCardArea(card.id) ~= Card.Void and room:getCardArea(card.id) ~= Card.Unknown
      end) then
        local moves = {}
        for _ = 1, 5, 1 do
          local c = room:printCard("charm", math.random(4), math.random(13))
          table.insert(moves, {
            ids = {c.id},
            toArea = Card.DrawPile,
            moveReason = fk.ReasonJustMove,
            skillName = self.name,
            proposer = player.id,
            moveVisible = true,
            drawPilePosition = math.random(#room.draw_pile),
          })
        end
        room:moveCards(table.unpack(moves))
      end
    end
  end,
}
local chuanwu = fk.CreateViewAsSkill{
  name = "rfenghou__chuanwu",
  pattern = ".",
  prompt = "#rfenghou__chuanwu",
  interaction = function (self, player)
    local all_names = player:getMark(self.name)
    return U.CardNameBox {
      choices = U.getViewAsCardNames(player, self.name, all_names),
      all_choices = all_names,
    }
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    if Fk.all_card_types[self.interaction.data] == nil then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    local room = player.room
    local copy = Fk.all_card_types[use.card.name]
    local card = room:printCard(copy.name, copy.suit, copy.number)
    room:moveCardTo(card, Card.Processing, nil, fk.ReasonUse)
    use.card:addSubcard(card.id)
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  enabled_at_response = function(self, player, response)
    return not response and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and
      #U.getViewAsCardNames(player, self.name, player:getMark(self.name)) > 0
  end,

  on_acquire = function (self, player, is_start)
    local all_names = {}
    local packNames = {"standard_cards", "maneuvering", "standard_ex_cards"}
    for _, name in ipairs(Fk.all_card_names) do
      local card = Fk:cloneCard(name)
      if not (card.package and table.contains(packNames, card.package.name)) then
        table.insertIfNeed(all_names, name)
      end
    end
    player.room:setPlayerMark(player, self.name, all_names)
  end,
}
emo:addSkill(zhufa)
emo:addSkill(chuanwu)
Fk:loadTranslationTable{
  ["rfenghou__n_emoprincess"] = "‮Ǝɯo‬",
  ["#rfenghou__n_emoprincess"] = "喑黒毀灭емо公主",
  ["designer:rfenghou__n_emoprincess"] = "RalphR&祭祀",
  --["illustrator:rfenghou__n_emoprincess"] = "",

  ["rfenghou__zhufa"] = "主法",
  [":rfenghou__zhufa"] = "锁定技，除【法】以外的伤害牌进入弃牌堆后，你将之移出游戏。若同名牌均移出，将五张【法】洗入牌堆。",
  ["rfenghou__chuanwu"] = "穿屋",
  --[":rfenghou__chuanwu"] = "每回合限一次，你可以将一张牌改变为任意一张牌使用。（以此法使用的牌会永久影响服务器中的此牌直到服务器重启！）",
  [":rfenghou__chuanwu"] = "每回合限一次，你可以从虚空中使用一张军争模式不可用的牌。",
  --["#rfenghou__chuanwu"] = "穿屋：将一张牌改变为任意一张牌使用",
  ["#rfenghou__chuanwu"] = "穿屋：使用一张牌",
}

local dogguy = General:new(extension, "rfenghou__dogguy", "fuyao", 4)
Fk:loadTranslationTable{
  ["rfenghou__dogguy"] = "狗",
  ["#rfenghou__dogguy"] = "3D领域大神",
  ["cv:rfenghou__dogguy"] = "",
  ["designer:rfenghou__dogguy"] = "低调的温柔",
  ["illustrator:rfenghou__dogguy"] = "AI",
}

-- 带狗通用池子
local daigou_normal = {

}

-- 带狗身份局池子
local daigou_role = {
  "steam__godhanxin", -- 蒸神韩信
  "steam__corrupted_bluebaby", -- 蒸堕化蓝人
  "steam__hollowknight", -- 蒸空洞骑士
  "steam__lazarus", -- 蒸拉撒路
  "steam__keeper", -- 蒸店长
  "rfenghou__murongke", -- 封侯慕容恪
  "moe__heimei", -- 萌包黑梅
  "steam__isaac", -- 蒸以撒
  "steam__nasus", -- 蒸内瑟斯
  "efengqi__godlvbu", -- 风起神吕布

  "steam__apollyon", -- 蒸亚玻伦
  "steam__trump", -- 蒸特朗普
  "steam__liuyan", -- 蒸刘焉
  "steam__zhugdan", -- 蒸诸葛诞
  "efengqi__caopi", -- 风起曹丕
  "steam__corrupted_apollyon", -- 蒸堕化亚玻伦

  "rfenghou__yingzheng", -- 封侯嬴政
  "steam__wenyang", -- 蒸文鸯（5血决斗哥）
  "steam__corrupted_eve", -- 蒸堕夏娃
  "rfenghou__shihu", -- 封侯石虎
  "steam__sunhao", -- 蒸孙皓
  "rfenghou__liuche", -- 封侯刘彻
  "tyj__abathur", -- 汤圆阿巴瑟
  "steam__chengtang", -- 蒸成汤
  "steam__jifa", -- 蒸姬发

  -- 第一代老东西
  "rfenghou__huanwen", -- 封侯桓温（浴霸哥）
  "steam__thutmose_third", -- 蒸法老，连击摸8哥
  "efengqi__zhangfei", -- 风起张飞
  "steam__azazel", --蒸阿撒泻勒（印兵临哥）
  "rfenghou__yuanziyou", -- 封侯元子攸（伏案双限定哥）
  "rfenghou__zhangxianzhong", -- 封侯张献忠
  "wanghe", -- 王龁
  "xiaobai-eleven__zhushixing", -- 小白朱士行（和尚哥）
  "efengqi__zhangliao", -- 风起张辽
  "rfenghou__jisi", -- 封侯先帝祭祀

  -- 老东西
  "rfenghou__simawei", -- 封侯司马玮
  "efengqi__luxun", -- 风起陆逊
  "efengqi__sunquan", -- 风起孙权
  "rfenghou__yangfenghanxian", -- 封侯杨奉韩暹
  "xiaobai__lishu", -- 小白李术
  "rfenghou__wangling", -- 封侯王凌
  "efengqi__caocao", -- 风起曹操
  "godwangjian", -- 神王翦
  "rfenghou__miaomiao", -- 封侯妙妙
}

-- 带狗斗地主池子
local daigou_1v2 = {
  "efengqi__guanyu", -- 风起关羽
  "rfenghou__yujig", -- 风起虞姬
  "steam__hornet", -- 蒸大黄蜂 
  "xiaobai-ten__fugu", -- 小白傅嘏
  "pangjuan", -- 汗青庞涓
  "tyj__hansui", -- 汤圆韩遂
  "ysch4__zhouxuan", -- 亦书成花周宣
  "ysch4__Jinx", -- 亦书成花金克丝
  "steam__godhanxin", -- 蒸神韩信
  "steam__godxunyu", -- 蒸神荀彧

  "rfenghou__th_kogasa", -- 封侯R神
  "xiaobai-eleven__lizhaoyi", -- 小白李昭仪
  "steam__shitao", -- 蒸石韬
  "steam__laizhonghui", -- 蒸来钟会
  "efengqi__liubei", -- 风起刘备
  "steam__jvshou", -- 蒸沮授

  "wanghe", -- 汗青王龁
  "sa__dianwei", -- S赛典韦
  "tea__zhangwen", -- 茶水张温
  "steam__liuchen", -- 蒸刘谌
  "moesp__xiajie", -- 萌夏桀
  "godlikui", -- 汗青神李悝
  "blitz__Thirty_Seven", -- 提瓦特闪击37
  "rfenghou__nero", -- 封侯尼禄
  "rfenghou__wangling", -- 封侯王凌
  "xiaobai-eleven__weidan", -- 小白韦诞
  "rfenghou__jisi", -- 封侯先帝祭祀
  "steam__simashi", -- 蒸司马师
  "ol__feiyi", -- OL费祎
}

-- 带狗2v2团战2池子
local daigou_2v2 = {
  "efengqi__lukang", -- 风起陆抗
  "xiaobai__zhugerong", -- 小白诸葛融
  "efengqi__luxun", -- 风起陆逊
  "efengqi__guanyu", -- 风起关羽
  "rfenghou__simawei", -- 封侯司马玮
  "xiaobai__jiyan", -- 小白暨艳（规矩哥）
  -- 牢R关小黑屋 "rfenghou__th_kogasa", -- 封侯R神
  "rfenghou__wangling", -- 封侯王凌
  "rfenghou__nero", -- 封侯尼禄
  "tiandan", -- 田单

  -- 老东西
  "xiaobai-ten__fugu", -- 小白傅嘏
  "efengqi__guojia", -- 风起郭嘉
  "rfenghou__xiangchong", -- 封侯向宠
  "efengqi__zhangliao", -- 风起张辽
  "rfenghou__caozhao", -- 封侯曹肇
}

--- 获取带狗池子并公示
---@return string[]
local getDaigouPool = function(room)
  local generals = table.simpleClone(daigou_normal)
  local exGenerals, excludeGnerals = {}, {}
  for _, p in ipairs(room.players) do
    table.insert(excludeGnerals, p.general)
    table.insert(excludeGnerals, p.deputyGeneral)
  end
  local mode = room.settings.gameMode
  if room:isGameMode("role_mode") or mode == "draft" then
    exGenerals = table.slice(daigou_role, 1, 11)
  elseif room:isGameMode("1v2_mode") then
    exGenerals = table.slice(daigou_1v2, 1, 11)
  elseif room:isGameMode("2v2_mode") then
    exGenerals = table.slice(daigou_2v2, 1, 11)
  else
    exGenerals = table.connect(daigou_role, daigou_1v2, daigou_2v2)
  end
  table.insertTableIfNeed(generals, exGenerals)
  generals = table.filter(generals, function(name) return Fk.generals[name] ~= nil and not table.contains(excludeGnerals, name) end)
  -- 是否仅能从房间开启武将中获取？
  local openBanList = false
  if openBanList then
    generals = table.filter(generals, function(name) return Fk:canUseGeneral(name) end)
  end
  if room:getBanner("@&rfenghou__daigou") == nil then
    room:setBanner("@&rfenghou__daigou", generals)
  end
  return generals
end

local daigou = fk.CreateActiveSkill{
  name = "rfenghou__daigou",
  card_num = 0,
  target_num = 1,
  card_filter = Util.FalseFunc,
  prompt = "#rfenghou__daigou",
  target_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.tos[1])
    local generals = getDaigouPool(room)
    if #generals == 0 then return end
    local orig = to.general
    local general = table.random(generals)
    room:findGeneral(general)
    room:changeHero(to, general, false, false, true, true, true)
    if to.general == general then -- 预防一下插结乱改武将
      to.tag["rfenghou__daigou_general"] = general
      to.tag["rfenghou__daigou_orig"] = orig
      to:chat(Fk:translate(general).."带条狗都能赢")
    end
  end,

  on_acquire = function (self, player, is_start)
    getDaigouPool(player.room)
  end,
}

local rfenghou__daigou_trigger = fk.CreateTriggerSkill {
  name = "#rfenghou__daigou_trigger",
  priority = 1.01, -- 优先于游戏开始时的其他技能
  events = {fk.GameStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(daigou) and daigou:canUse(player)
  end,
  on_cost = function (self, event, target, player, data)
    local targets = table.map(player.room.alive_players, Util.IdMapper)
    local tos = player.room:askForChoosePlayers(player, targets, 1, 1, "#rfenghou__daigou", self.name, true)
    if #tos > 0 then
      self.cost_data = {tos = tos}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    player:addSkillUseHistory(daigou.name, 1)
    daigou:onUse(player.room, {from = player.id, tos = self.cost_data.tos, cards = {}})
  end,

  -- 仅用于发送骚话
  refresh_events = {fk.BeforeGameOverJudge, fk.Damaged, fk.AfterPropertyChange, fk.GameFinished},
  can_refresh = function(self, event, target, player, data)
    local generalRecord = player.tag["rfenghou__daigou_general"]
    if generalRecord == nil then return false end
    if event == fk.BeforeGameOverJudge then
      return data.damage and data.damage.from == player
    elseif event == fk.Damaged then
      return data.from == player and data.damage > 2 and not target.dead
    elseif event == fk.AfterPropertyChange then
      return target == player and data.results and data.results["generalChange"] and data.results["generalChange"][1] == generalRecord
    elseif event == fk.GameFinished then
      return true
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local general = player.general
    local generalRecord = player.tag["rfenghou__daigou_general"]
    local nametrans = Fk:translate(generalRecord)
    local room = player.room
    if event == fk.AfterPropertyChange then
      -- 由带狗武将变为其他武将时发送
      player:chat("保留我的"..nametrans.."吧")
    elseif event == fk.GameFinished then
      -- 游戏结束时，切换为原武将（为了胜率统计
      local orig = player.tag["rfenghou__daigou_orig"]
      if orig then
        room:setPlayerProperty(player, "general", orig)
        -- 如果赢了，则得意
        if data and type(data) == "string" then
          if string.find(data, player.role) then
            player:chat(nametrans .. " 比 " .. Fk:translate(orig) .. " 强多了!")
          else
            player:chat("感觉 " .. nametrans .." 被严重高估…")
          end
        end
      end
    else
      -- 带狗武将杀死角色或造成3点伤害后，受伤角色怒骂道
      if general == generalRecord then
        target:chat("狗设计的！")
      else
        -- 判断一下变将
        target:chat(nametrans .."真是狗设计的！")
      end
    end
  end,
}
daigou:addRelatedSkill(rfenghou__daigou_trigger)
dogguy:addSkill(daigou)

Fk:loadTranslationTable{
  ["rfenghou__daigou"] = "带狗",
  [":rfenghou__daigou"] = "限定技，游戏开始时，或出牌阶段，你可以令一名角色变成“xx带条狗都能赢”池子中的随机一名武将。",
  ["#rfenghou__daigou"] = "带狗：令一名角色变成“xx带条狗都能赢”池子中一名武将",
  ["#rfenghou__daigou_trigger"] = "带狗",
  ["@&rfenghou__daigou"] = "带狗将池",
}


local xiaoyezi = General:new(extension, "rfenghou__xiaoyezi", "fuyao", 4)
Fk:loadTranslationTable{
  ["rfenghou__xiaoyezi"] = "小叶子",
  ["#rfenghou__xiaoyezi"] = "戒指老爷爷",
  ["cv:rfenghou__xiaoyezi"] = "",
  ["designer:rfenghou__xiaoyezi"] = "妙阿",
  ["illustrator:rfenghou__xiaoyezi"] = "Family Guy",
}

--- 将一名角色的武将牌置入场上的【木牛流马】
---@param proposer ServerPlayer
---@param target ServerPlayer
---@param skillName string
---@param general? string @ 需要移除的武将，不填则自选
local putGeneralToWoodenOx = function (proposer, target, skillName, general)
  local room = proposer.room
  local deputy = false
  local shibing = target.gender == General.Male and "blank_shibing" or "blank_nvshibing"
  if target.general == general then
    deputy = false
  elseif target.deputyGeneral == general then
    deputy = true
  else
    local choices = {target.general}
    if target.deputyGeneral ~= "" then
      table.insert(choices, target.deputyGeneral)
    end
    general = room:askForChoice(target, choices, skillName, "")
    deputy = general == target.deputyGeneral
  end
  room:changeHero(target, shibing, false, deputy, true, false, true)
  local receiver
  local woodenOwner = table.map(table.filter(room.alive_players, function(p)
    return table.find(p:getCardIds("e"), function (id) return Fk:getCardById(id, true).trueName == "wooden_ox" end) ~= nil
  end), Util.IdMapper)
  if #woodenOwner == 0 then return end
  if #woodenOwner == 1 then
    receiver = woodenOwner[1]
  else
    receiver = room:askForChoosePlayers(proposer, woodenOwner, 1, 1, nil, skillName, false)[1]
  end
  receiver = room:getPlayerById(receiver)
  local generalcard = room:printCard("generalcard", math.random(4), math.random(13))
  room:setCardMark(generalcard, "@generalcard", Fk:translate(general))---FIXME:cardMark没有自动翻译，服了
  room:setCardMark(generalcard, "generalcard", general)
  receiver:addToPile("$role_carriage", generalcard.id, true, skillName)
end

local najie = fk.CreateTriggerSkill{
  name = "rfenghou__najie",
  anim_type = "control",
  events = {fk.TurnStart, fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target == player then
      if event == fk.TurnStart then
        return #player:getAvailableEquipSlots(Card.SubtypeTreasure) > 0 and table.find(player:getCardIds("e"), function (id)
          return Fk:getCardById(id).sub_type == Card.SubtypeTreasure
        end) == nil
      elseif data.damage >= (player.hp + player.shield) then
        return table.find(player.room.alive_players, function(p)
          return p.general == "rfenghou__xiaoyezi" or p.deputyGeneral == "rfenghou__xiaoyezi"
        end) ~= nil
        and table.find(player.room.alive_players, function(p)
          return table.find(p:getCardIds("e"), function (id) return Fk:getCardById(id, true).trueName == "wooden_ox" end) ~= nil
        end) ~= nil
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.TurnStart then return true end
    return player.room:askForSkillInvoke(player, self.name, nil, "#rfenghou__najie-ask")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      local name = "rfenghou__wooden_ox"
      if Fk.all_card_types[name] == nil then return end
      local cid = room:getTag("rfenghou__najie_record")
      if cid == nil then
        for _, id in ipairs(Fk:getAllCardIds()) do
          if Fk:getCardById(id, true).name == name then
            cid = id
            break
          end
        end
        -- 如果卡组没开启，打印一张木马
        if not cid then
          cid = room:printCard(name, Card.Diamond, 5).id
        end
        room:setTag("rfenghou__najie_record", cid)
      end
      room:moveCardIntoEquip(player, cid, self.name, false, player.id)
      local skill = Fk.skills["rfenghou__wooden_ox_skill"]
      if skill and player:hasSkill(skill) then
        player:addToPile("$role_carriage", room:getNCards(2), false, self.name)
      end
    else
      local targets = table.map(table.filter(room.alive_players, function(p)
        return p.general == "rfenghou__xiaoyezi" or p.deputyGeneral == "rfenghou__xiaoyezi"
      end), Util.IdMapper)
      local to
      if #targets == 0 then return end
      if #targets == 1 then
        to = targets[1]
      else
        to = room:askForChoosePlayers(player, targets, 1, 1, "#rfenghou__najie-choose", self.name, false)[1]
      end
      to = room:getPlayerById(to)
      putGeneralToWoodenOx(player, to, self.name, "rfenghou__xiaoyezi")
      return true
    end
  end,
}
xiaoyezi:addSkill(najie)

Fk:loadTranslationTable{
  ["rfenghou__najie"] = "纳戒",
  [":rfenghou__najie"] = "回合开始时，若你的装备区没宝物牌，将【木牛流马】置入你的装备区，再将牌堆顶两张牌置入仓廪“辎”中；你受到致命伤害时，可以将“小叶子”置入场上的【木牛流马】防止之。",
  ["#rfenghou__najie-choose"] = "纳戒：你须选择一个“小叶子”，将其置入【木牛流马】！",
  ["#rfenghou__najie-ask"] = "纳戒：你可将“小叶子”置入场上的【木牛流马】防止即将受到的致命伤害！",
}

-- 判断一名角色是否有可移除的武将牌
---@param player ServerPlayer
local availableGeneral = function (player)
  return table.find({player.general, player.deputyGeneral}, function (name)
    local general = Fk.generals[name]
    return general and general ~= "blank_shibing" and general ~= "blank_nvshibing" and name ~= "hiddenone" and name ~= "anjiang"
  end) ~= nil
end

local fenjue = fk.CreateTriggerSkill{
  name = "rfenghou__fenjue",
  anim_type = "offensive",
  events = {fk.PreDamage, fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.PreDamage then
        return target == player and data.damageType ~= fk.FireDamage
      elseif target ~= player and data.damageType == fk.FireDamage then
        return availableGeneral(target)
        and table.find(player.room.alive_players, function(p)
          return table.find(p:getCardIds("e"), function (id) return Fk:getCardById(id, true).trueName == "wooden_ox" end) ~= nil
        end) ~= nil
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.PreDamage then
      return player.room:askForSkillInvoke(player, self.name, nil, "#rfenghou__fenjue-damage:"..data.to.id)
    else
      return player.room:askForSkillInvoke(target, self.name, nil, "#rfenghou__fenjue-remove:::"..data.damage)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.PreDamage then
      data.damageType = fk.FireDamage
    else
      putGeneralToWoodenOx(target, target, self.name)
      return true
    end
  end,
}
xiaoyezi:addSkill(fenjue)

Fk:loadTranslationTable{
  ["rfenghou__fenjue"] = "焚诀",
  [":rfenghou__fenjue"] = "当你造成伤害时，可以改为造成火焰伤害；其他角色受到火焰伤害时，可以将武将牌置入场上的【木牛流马】防止之。",
  ["#rfenghou__fenjue-damage"] = "焚诀：你可以将对 %src 造成的伤害改为火焰伤害",
  ["#rfenghou__fenjue-remove"] = "焚诀：你可将武将牌置入场上的【木牛流马】防止你受到 %arg 点火焰伤害",
}

local ifyidaju = General:new(extension, "rfenghouif__yidaju", "fuyao", 4)
Fk:loadTranslationTable{
  ["rfenghouif__yidaju"] = "if易大剧",
  ["#rfenghouif__yidaju"] = "音乐或伟业",
  ["cv:rfenghouif__yidaju"] = "",
  ["designer:rfenghouif__yidaju"] = "妙阿",
  ["illustrator:rfenghouif__yidaju"] = "Caine",
  ["~rfenghouif__yidaju"] = "",
}

local qizhiyuci = fk.CreateTriggerSkill{
  name = "rfenghou__qizhiyuci",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target == player then
      return player.phase == Player.Draw or player.phase == Player.Discard
    end
  end,
  on_cost = function (self, event, target, player, data)
    return player.phase == Player.Discard or player.room:askForSkillInvoke(player, self.name, nil, "#rfenghou__qizhiyuci-skipdraw")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player.phase == Player.Draw then
      local tos = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 999,
      "#rfenghou__qizhiyuci-draw", self.name, true)
      if #tos > 0 then
        for _, to in ipairs(table.map(tos, Util.Id2PlayerMapper)) do
          if not to.dead then
            to:drawCards(1, self.name)
          end
        end
      end
      return true
    else
      room:askForDiscard(player, 1, 999, false, "phase_discard", true, nil, "#rfenghou__qizhiyuci-discard")
      local tos = table.filter(room:getAlivePlayers(), function (p)
        return p:getHandcardNum() > player:getHandcardNum()
      end)
      if #tos > 0 then
        room:doIndicate(player.id, table.map(tos, Util.IdMapper))
        for _, to in ipairs(tos) do
          if not to.dead then
            room:askForDiscard(to, 1, 1, true, self.name, false)
          end
        end
        return true
      end
    end
  end,
}
ifyidaju:addSkill(qizhiyuci)

Fk:loadTranslationTable{
  ["rfenghou__qizhiyuci"] = "弃置于此",
  [":rfenghou__qizhiyuci"] = "摸牌阶段，你可以放弃摸牌，令任意名角色依次摸一张牌；弃牌阶段，你须改为弃任意张手牌，然后令手牌数大于你的角色依次弃一张牌。",
  ["#rfenghou__qizhiyuci-skipdraw"] = "弃置于此：你可以放弃摸牌，令任意名角色各摸一张牌",
  ["#rfenghou__qizhiyuci-draw"] = "弃置于此：令任意名角色依次摸一张牌",
  ["#rfenghou__qizhiyuci-discard"] = "弃置于此：请弃任意张手牌，然后令手牌数大于你的角色依次弃一张牌",
}

local fenqinkaochang = fk.CreateTriggerSkill{
  name = "rfenghou__fenqinkaochang",
  mute = true,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    local room = player.room
    -- 不考虑多个移动的情况，懒
    local guy
    for _, move in ipairs(data) do
      local temp = room:getPlayerById(move.to)
      if temp and temp:isAlive() and move.toArea == Card.PlayerHand
      and table.every(room.alive_players, function(p) return p:getHandcardNum() <= temp:getHandcardNum() end) then
        guy = temp
        break
      end
      temp = room:getPlayerById(move.from)
      if temp and temp:isAlive() and table.find(move.moveInfo, function (info)
        return info.fromArea == Card.PlayerHand
      end)
      and table.every(room.alive_players, function(p) return p:getHandcardNum() <= temp:getHandcardNum() end) then
        guy = temp
        break
      end
    end
    if guy then
      self.cost_data = guy.id
      return true
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local last = room:getPlayerById(player:getMark(self.name))
    room:setPlayerMark(player, self.name, to.id)
    room:setPlayerMark(player, "@rfenghou__fenqinkaochang", to.general)
    if last and last:isAlive() and last ~= to then
      if room:askForSkillInvoke(to, self.name, nil, "#rfenghou__fenqinkaochang-damage:"..last.id) then
        player:broadcastSkillInvoke(self.name)
        room:notifySkillInvoked(to, self.name, "offensive", {last.id})
        room:doIndicate(to.id, {last.id})
        room:damage { from = to, to = last, damage = 1, skillName = self.name, damageType = fk.FireDamage }
      end
    end
  end,

  on_lose = function (self, player)
    player.room:setPlayerMark(player, "@rfenghou__fenqinkaochang", 0)
  end,
}
ifyidaju:addSkill(fenqinkaochang)

Fk:loadTranslationTable{
  ["rfenghou__fenqinkaochang"] = "焚琴烤肠",
  [":rfenghou__fenqinkaochang"] = "当一名角色手牌数变化后，若其手牌数全场最多，记录之，然后其可以对记录的上一名角色造成一点火焰伤害。",
  ["@rfenghou__fenqinkaochang"] = "焚琴烤肠",
  ["#rfenghou__fenqinkaochang-damage"] = "焚琴烤肠：你可以对 %src 造成1点火焰伤害",
}

local tiexuezaizao = fk.CreateTriggerSkill{
  name = "rfenghou__tiexuezaizao",
  events = {fk.TurnStart},
  frequency = Skill.Limited,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room:getAlivePlayers()) do
      if not p.dead then
        if not p.chained then
          p:setChainState(true)
        end
        if not p.dead then
          room:setPlayerMark(p, "@@rfenghou__tiexuezaizao-turn", 1)
        end
      end
    end
  end,
}

local tiexuezaizao_delay = fk.CreateTriggerSkill{
  name = "#rfenghou__tiexuezaizao_delay",
  events = {fk.BeforeChainStateChange},
  frequency = Skill.Compulsory,
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player.chained and not player.dead
    and player:getMark("@@rfenghou__tiexuezaizao-turn") ~= 0
  end,
  on_cost = Util.TrueFunc,
  on_use = Util.TrueFunc,
}
tiexuezaizao:addRelatedSkill(tiexuezaizao_delay)
ifyidaju:addSkill(tiexuezaizao)

Fk:loadTranslationTable{
  ["rfenghou__tiexuezaizao"] = "血铁再造",
  [":rfenghou__tiexuezaizao"] = "限定技，回合开始时，你可以令所有角色横置，且本回合不能重置。",
  ["@@rfenghou__tiexuezaizao-turn"] = "血铁再造",
  ["#rfenghou__tiexuezaizao_delay"] = "血铁再造",

  ["$rfenghou__tiexuezaizao1"] = "",
  ["$rfenghou__tiexuezaizao2"] = "",
}

local cyc = General:new(extension, "rfenghou__cyc", "fuyao", 4)
Fk:loadTranslationTable{
  ["rfenghou__cyc"] = "cyc",
  ["#rfenghou__cyc"] = "决斗领域",
  ["cv:rfenghou__cyc"] = "",
  ["designer:rfenghou__cyc"] = "妙阿",
  ["illustrator:rfenghou__cyc"] = "",
}

local peng = fk.CreateTriggerSkill{
  name = "rfenghou__pengskill",
  events = {fk.AfterCardsMove},
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    local ids = {}
    for _, move in ipairs(data) do
      if move.toArea == Player.Hand then
        for _, info in ipairs(move.moveInfo) do
          if table.contains(player.player_cards[Player.Hand], info.cardId) then
            Fk:filterCard(info.cardId, player)
            local c = Fk:getCardById(info.cardId)
            if c.type == Card.TypeBasic and c.name ~= "peng" then
              table.insertIfNeed(ids, info.cardId)
            end
          end
        end
      end
    end
    if #ids > 0 then
      self.cost_data = {cards = ids}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = table.simpleClone(self.cost_data.cards)
    room:throwCard(cards, self.name, player, player)
    if player.dead then return end
    room:delay(100)
    local get = {}
    for i = 1, #cards * 2 do
      table.insert(get, room:printCard("peng", math.random(4), 12).id)
    end
    room:obtainCard(player, get, true, fk.ReasonJustMove, player.id, self.name)
  end,
}
local peng_maxcards = fk.CreateMaxCardsSkill{
  name = "#rfenghou__pengskill_maxcards",
  exclude_from = function(self, player, card)
    return card and card.trueName == "peng" and player:hasSkill(peng)
  end,
}
peng:addRelatedSkill(peng_maxcards)

cyc:addSkill(peng)

Fk:loadTranslationTable{
  ["rfenghou__pengskill"] = "嘭！",
  [":rfenghou__pengskill"] = "锁定技，你获得其他基本牌后弃置之，并获得双倍数量的【嘭！】。你的【嘭！】不计入手牌上限。",
}

local douma = fk.CreateViewAsSkill{
  name = "rfenghou__douma",
  anim_type = "offensive",
  --pattern = ".|.|.|.|.|trick,basic",
  prompt = function (self, selected_cards, selected)
    local mark = Self:getMark("@rfenghou__douma")
    if type(mark) == "string" then
      return "#rfenghou__douma:::"..mark
    end
    return " "
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).name == "peng"
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return nil end
    local mark = Self:getMark("@rfenghou__douma")
    if Fk.all_card_types[mark] == nil then return nil end
    local c = Fk:cloneCard(mark)
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 -- stupid mainSkill
    and player:getMark("@rfenghou__douma") ~= 0
  end,
  enabled_at_response = Util.FalseFunc,

  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@rfenghou__douma", 0)
  end,
}
local douma_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou__douma_trigger",
  mute = true,
  events = {fk.PreCardEffect},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(douma) and not player:isKongcheng() and data.to == player.id then
      return data.card.type == Card.TypeTrick or data.card.is_damage_card or data.card.name == "peng"
    end
  end,
  on_cost = function (self, event, target, player, data)
    local num = RUtil.cardNameLen(data.card)
    if num == 0 then return false end
    local cards = player.room:askForDiscard(player, num, num, false, self.name, true, "peng", "#rfenghou__douma-cost:::"..num..":"..data.card:toLogString(), true)
    if #cards == num then
      self.cost_data = {cards = cards}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(douma.name)
    room:notifySkillInvoked(player, self.name, "defensive")
    room:setPlayerMark(player, "@rfenghou__douma", data.card.name)
    room:throwCard(self.cost_data.cards, self.name, player, player)
    return true
  end,
}
douma:addRelatedSkill(douma_trigger)

cyc:addSkill(douma)

Fk:loadTranslationTable{
  ["rfenghou__douma"] = "斗？",
  [":rfenghou__douma"] = "锦囊牌或伤害牌对你生效前，你可以弃置此牌牌名字数张【嘭！】令之无效；出牌阶段限一次，你可以将一张【嘭！】当作上次以此法响应的牌使用。",
  ["@rfenghou__douma"] = "斗？",
  ["#rfenghou__douma_trigger"] = "斗？",
  ["#rfenghou__douma-cost"] = "斗？：你可以弃置%arg张【嘭！】令%arg2无效",
  ["#rfenghou__douma"] = "斗？：将一张【嘭！】当【%arg】使用",
}

local wanla = fk.CreateTriggerSkill{
  name = "rfenghou__wanla",
  anim_type = "offensive",
  frequency = Skill.Limited,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
    and target ~= player and target.phase == Player.Finish and not target.dead then
      local num = #table.filter(player.player_cards[Player.Hand], function(id)
        return Fk:getCardById(id).name == "peng"
      end)
      return num > 0 and num > (target.hp + target:getHandcardNum())
    end
  end,
  on_cost = function (self, event, target, player, data)
    if player.room:askForSkillInvoke(player, self.name, nil, "#rfenghou__wanla-ask:"..target.id) then
      self.cost_data = {tos = {target.id}}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    while not player.dead and not target.dead do
      local card
      for _, id in ipairs(player.player_cards[Player.Hand]) do
        local c = Fk:getCardById(id)
        if c.name == "peng" and not player:prohibitUse(c) and not player:isProhibited(target, c) then
          card = c
          break
        end
      end
      if not card then break end
      room:useCard{from = player.id, tos = {{target.id}}, card = card}
    end
  end,
}
cyc:addSkill(wanla)

Fk:loadTranslationTable{
  ["rfenghou__wanla"] = "完。",
  [":rfenghou__wanla"] = "限定技，其他角色结束阶段，若其手牌数与体力值之和小于你的【嘭！】数，你可以对其使用所有【嘭！】。",
  ["#rfenghou__wanla-ask"] = "完：你可以对 %src 使用所有【嘭！】",

  ["rfenghou__wanla1"] = "",
  ["rfenghou__wanla2"] = "",
}

local ifpangpang = General:new(extension, "rfenghouif__pangpang", "fuyao", 3)


Fk:loadTranslationTable{
  ["rfenghouif__pangpang"] = "if胖即是胖",
  ["#rfenghouif__pangpang"] = "@全体美员",
  ["designer:rfenghouif__pangpang"] = "勿念·陆风先生",
  ["illustrator:rfenghouif__pangpang"] = "AI",
}


local xinyuekuangchao = fk.CreateActiveSkill{
  name = "rfenghou__xinyuekuangchao",
  anim_type = "drawcard",
  card_num = 0,
  target_num = 0,
  times = function (self)
    return (1 + Self:getMark("rfenghou__quanminrelang_success")) - Self:usedSkillTimes(self.name, Player.HistoryPhase)
  end,
  prompt = "#rfenghou__xinyuekuangchao",
  card_filter = Util.FalseFunc,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < (1 + player:getMark("rfenghou__quanminrelang_success"))
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local players = room:getAlivePlayers()
    room:doIndicate(player.id, table.map(players, Util.IdMapper))
    local color, cardtype, suit
    local colors, types, suits = {}, {}, {}
    local function checkFill(p) -- 检测中央区是否缺少颜色花色类型，重铸前不写参数，重铸后参数填重铸者
      if color == nil then
        colors = {}
        for _, id in ipairs(room:getBanner("@$CenterArea")) do
          if Fk:getCardById(id).color ~= Card.NoColor then
            table.insertIfNeed(colors, Fk:getCardById(id).color)
          end
        end
        if #colors == 2 then color = p or true end
      end
      if cardtype == nil then
        types = {}
        for _, id in ipairs(room:getBanner("@$CenterArea")) do
          table.insertIfNeed(types, Fk:getCardById(id).type)
        end
        if #types == 3 then cardtype = p or true end
      end
      if suit == nil then
        suits = {}
        for _, id in ipairs(room:getBanner("@$CenterArea")) do
          if Fk:getCardById(id).suit ~= Card.NoSuit then
            table.insertIfNeed(suits, Fk:getCardById(id).suit)
          end
        end
        if #suits == 4 then suit = p or true end
      end
    end
    for _, p in ipairs(players) do
      if not p.dead and not p:isNude() then
        checkFill()
        local cids = room:askForCard(p, 1, 1, true, self.name, false, nil, "#rfenghou__xinyuekuangchao-recast")
        room:recastCard(cids, p, self.name)
        checkFill(p)
        if not color then
          colors = {}
          for _, id in ipairs(room:getBanner("@$CenterArea")) do
            if Fk:getCardById(id).color ~= Card.NoColor then
              table.insertIfNeed(colors, Fk:getCardById(id).color)
            end
          end
          if #colors == 2 then
            color = p
          end
        end
        if not cardtype then
          types = {}
          for _, id in ipairs(room:getBanner("@$CenterArea")) do
            table.insertIfNeed(types, Fk:getCardById(id).type)
          end
          if #types == 3 then
            cardtype = p
          end
        end
        if not suit then
          suits = {}
          for _, id in ipairs(room:getBanner("@$CenterArea")) do
            if Fk:getCardById(id).suit ~= Card.NoSuit then
              table.insertIfNeed(suits, Fk:getCardById(id).suit)
            end
          end
          if #suits == 4 then
            suit = p
          end
        end
      end
    end
    for _, v in ipairs({color, cardtype, suit}) do
      if v and type(v) == "table" then
        if not player.dead then
          player:drawCards(1, self.name)
        end
        if not v.dead then
          v:drawCards(1, self.name)
        end
      end
    end
  end,
}
xinyuekuangchao.CenterArea = true
ifpangpang:addSkill(xinyuekuangchao)
Fk:loadTranslationTable{
  ["rfenghou__xinyuekuangchao"] = "新月狂潮",
  [":rfenghou__xinyuekuangchao"] = "出牌阶段限一次，你可以令所有角色依次重铸一张牌，此过程中因此使中央区的颜色、类型、花色补齐的角色分别与你各摸一张牌。",
  ["#rfenghou__xinyuekuangchao"] = "令所有角色依次重铸一张牌",
  ["#rfenghou__xinyuekuangchao-recast"] = "新月狂潮:重铸一张牌",
}


local function startCircle(player, points)
  local room = player.room
  points = points or {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
  table.shuffle(points)
  room:setPlayerMark(player, "@[numring]quanminrelang", {
    all = points, ok = {}
  })
end

--- 返回下一个能点亮圆环的点数
---@return integer[]
local function getCircleProceed(value)
  if type(value) ~= "table" then return Util.DummyTable end
  local all_points = value.all
  local ok_points = value.ok -- 已经点亮的数字
  local all_len = #all_points
  -- 若没有点亮的就全部都满足
  if #ok_points == 0 then return all_points end
  -- 若全部点亮了返回空表
  if #ok_points == all_len then return Util.DummyTable end

  local function c(idx)
    if idx == 0 then idx = all_len end
    if idx == all_len + 1 then idx = 1 end
    return idx
  end

  -- 否则，显示相邻的，逻辑上要构成循环
  local ok_map = {}
  for _, v in ipairs(ok_points) do ok_map[v] = true end
  local start_idx, end_idx
  for i, v in ipairs(all_points) do
    -- 前一个不亮，这个是左端
    if ok_map[v] and not ok_map[all_points[c(i-1)]] then
      start_idx = i
    end
    -- 后一个不亮，这个是右端
    if ok_map[v] and not ok_map[all_points[c(i+1)]] then
      end_idx = i
    end
  end

  start_idx = c(start_idx - 1)
  end_idx = c(end_idx + 1)

  if start_idx == end_idx then
    return { all_points[start_idx] }
  else
    return { all_points[start_idx], all_points[end_idx] }
  end
end

local quanminrelang = fk.CreateTriggerSkill{
  name = "rfenghou__quanminrelang",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    local proceed = getCircleProceed(player:getMark("@[numring]quanminrelang"))
    for _, move in ipairs(data) do
      if move.toArea == Card.DiscardPile then
        for _, info in ipairs(move.moveInfo) do
          local number = Fk:getCardById(info.cardId).number
          if table.contains(proceed, number) then return true end
        end
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local circle_data = player:getMark("@[numring]quanminrelang")
    local proceed = getCircleProceed(circle_data)
    local completed = false
    for _, move in ipairs(data) do
      if move.toArea == Card.DiscardPile then
        for _, info in ipairs(move.moveInfo) do
          local number = Fk:getCardById(info.cardId).number
          if table.contains(proceed, number) then
            table.insert(circle_data.ok, number)
            proceed = getCircleProceed(circle_data)
            if proceed == Util.DummyTable then -- 已完成圆环则立即停止结算
              completed = true
              goto BREAK
            end
          end
        end
      end
    end
    ::BREAK::

    if completed then
      local all = circle_data.all
      startCircle(player, all)

      local ids = {}
      for _, id in ipairs(room:getBanner("@$CenterArea")) do
        if Fk:getCardById(id).type == Card.TypeBasic then
          table.insert(ids, id)
        end
      end
      if #ids > 0 then
        room:askForYiji(player, ids, room.alive_players, self.name, 0, #ids, "#rfenghou__quanminrelang-give", ids)
      end
      room:addPlayerMark(player, "rfenghou__quanminrelang_success")
    else
      room:setPlayerMark(player, "@[numring]quanminrelang", circle_data)
    end
  end,

  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@[numring]quanminrelang", 0)
    startCircle(player)
  end,
}

local quanminrelang_start = fk.CreateTriggerSkill{
  name = "#rfenghou__quanminrelang_start",
  main_skill = quanminrelang,
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(quanminrelang) and player:getMark("@[numring]quanminrelang") == 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player:broadcastSkillInvoke("rfenghou__quanminrelang")
    startCircle(player)
  end
}
quanminrelang:addRelatedSkill(quanminrelang_start)

quanminrelang.CenterArea = true
ifpangpang:addSkill(quanminrelang)

-- 照抄刘徽割圆
Fk:addQmlMark{
  name = "numring",
  how_to_show = function(name, value)
    -- FIXME: 神秘bug导致value可能为空串有待排查
    if type(value) ~= "table" then return " " end
    local nums = getCircleProceed(value)
    if #nums == 1 then
      return Card:getNumberStr(nums[1])
    elseif #nums == 2 then
      return Card:getNumberStr(nums[1]) .. Card:getNumberStr(nums[2])
    else
      return " "
    end
  end,
  qml_path = "packages/aaa_fenghou/qml/NumberRingBox"
}



Fk:loadTranslationTable{
  ["rfenghou__quanminrelang"] = "全民热浪",
  [":rfenghou__quanminrelang"] = "锁定技，游戏开始时，你将A~K所有点数随机排列成圆环，有牌进入弃牌堆后，将满足圆环进度的点数记录在圆环内。当圆环完成后，你分配中央区的所有基本牌并获得一个新的圆环。你每完成一次圆环，“新月狂潮”发动次数上限便+1(至多为5)。",
  ["@[numring]quanminrelang"] = "全民热浪",
  ["#rfenghou__quanminrelang-give"] = "全民热浪：请分配中央区的基本牌",

}

local tangyuan = General:new(extension, "rfenghou__tangyuan", "fuyao", 5)

Fk:loadTranslationTable{
  ["rfenghou__tangyuan"] = "汤圆",
  ["#rfenghou__tangyuan"] = "不是你真丢蹈节啊？",
  ["designer:rfenghou__tangyuan"] = "屑",
  ["illustrator:rfenghou__tangyuan"] = "",
}

--- 判断某事件是否为指定父事件的子事件
local function isParent(son, pat)
  local temp = son
  repeat
    if temp.id == pat.id then return true end
    temp = temp.parent
  until temp == nil
  return false
end

--- 使用的牌是否为回复牌
---@param event GameEvent @ 使用事件
local function isRecoverCard(event)
  local use = event.data[1]
  local card = use.card
  if table.contains({"god_salvation", "peach"}, card.trueName) then return true end
  -- 搜寻使用过程中此牌是否造成回复体力，可用于搜索濒死喝酒、受伤喝散
  return #event:searchEvents(GameEvent.Recover, 1, function (e)
    local recover = e.data[1]
    return recover.card == card and isParent(e, event)
  end) > 0
end

local daojie = fk.CreateTriggerSkill{
  name = "rfenghou__daojie",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    -- 我到底是不是汤圆啊？
    --if player.general ~= "rfenghou__tangyuan" and player.deputyGeneral ~= "rfenghou__tangyuan" then return false end
    local room = player.room
    local recoverd_players = {player}
    if target ~= player and player:hasSkill("rfenghou__tonggui") then
      room.logic:getEventsOfScope(GameEvent.Recover, 1, function (e)
        local recover = e.data[1]
        table.insertIfNeed(recoverd_players, recover.who)
        return false
      end, Player.HistoryGame)
    end
    if not table.contains(recoverd_players, target) then return false end
    local use_event = room.logic:getCurrentEvent()
    if use_event:findParent(GameEvent.Turn) == nil then return false end
    local cardlist = data.card:isVirtual() and data.card.subcards or {data.card.id}
    if #cardlist == 0 or not table.every(cardlist, function (id)
      return room:getCardArea(id) == Card.Processing
    end) then return false end
    local recover = player:hasSkill("rfenghou__guofu")
    local function fitCard(e)
      local c = e.data[1].card
      return (c:isCommonTrick() and not c.is_damage_card) or (recover and isRecoverCard(e))
    end
    if not fitCard(use_event) then return false end
    local first_id = -1
    room.logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
      local use = e.data[1]
      if use.from == target.id and fitCard(e) then
        first_id = e.id
        return true
      end
      return false
    end, Player.HistoryTurn)
    return use_event.id == first_id
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local skills = {}
    for _, skill in ipairs(player.player_skills) do
      if skill.frequency == Skill.Compulsory and skill:isPlayerSkill(player) then
        table.insert(skills, skill.name)
      end
    end
    table.insert(skills, "daojie_cancel")
    local choice = room:askForChoice(player, skills, self.name, "#rfenghou__daojie-choice", true)
    if choice == "daojie_cancel" then
      room:loseHp(player, 1, self.name)
    else
      room:handleAddLoseSkills(player, "-"..choice, nil, true, false)
    end
    if not player.dead and table.every(Card:getIdList(data.card), function (id)
      return room:getCardArea(id) == Card.Processing
    end) then
      local recoverd_players = {}
      room.logic:getEventsOfScope(GameEvent.Recover, 1, function (e)
        local recover = e.data[1]
        table.insertIfNeed(recoverd_players, recover.who)
        return false
      end, Player.HistoryGame)
      local targets = table.map(table.filter(room.alive_players, function (p)
        return p.kingdom == "fuyao" or p.kingdom == "fuyaoz"
        or (player:hasSkill("rfenghou__fuyaoo") and not table.contains(recoverd_players, p))
      end), Util.IdMapper)
      if #targets == 0 then return end
      if #targets > 1 then
        targets = room:askForChoosePlayers(player, targets, 1, 1, "#rfenghou__daojie-choose:::"..data.card:toLogString(), self.name, false)
      end
      room:obtainCard(targets[1], data.card, true, fk.ReasonPrey, player.id, self.name)
    end
  end,
}
tangyuan:addSkill(daojie)

Fk:loadTranslationTable{
  ["rfenghou__daojie"] = "蹈节",
  -- 若此牌仍在处理区
  [":rfenghou__daojie"] = "锁定技，当你每回合首次使用非伤害类普通锦囊牌后，汤圆须选择一项：1.失去1点体力；2.失去一个锁定技。然后令一名扶摇势力角色获得此牌。",
  ["#rfenghou__daojie-choice"] = "蹈节：选择失去一个锁定技，或失去1点体力",
  ["#rfenghou__daojie-choose"] = "蹈节：令一名符合角色获得此%arg",
  ["daojie_cancel"] = "取消",
  [":daojie_cancel"] = "失去1点体力",
}

local tonggui = fk.CreateTriggerSkill{
  name = "rfenghou__tonggui",
  frequency = Skill.Compulsory,
  can_trigger = Util.FalseFunc,
}
tangyuan:addSkill(tonggui)

Fk:loadTranslationTable{
  ["rfenghou__tonggui"] = "同归",
  [":rfenghou__tonggui"] = "锁定技，回复过体力的角色在“蹈节”中视为“你”。",
}

local guofu = fk.CreateTriggerSkill{
  name = "rfenghou__guofu",
  frequency = Skill.Compulsory,
  can_trigger = Util.FalseFunc,
}
tangyuan:addSkill(guofu)

Fk:loadTranslationTable{
  ["rfenghou__guofu"] = "果腹",
  [":rfenghou__guofu"] = "锁定技，回复牌在“蹈节”中视为“非伤害类普通锦囊牌”。",
}

local fuyaoo = fk.CreateTriggerSkill{
  name = "rfenghou__fuyaoo",
  frequency = Skill.Compulsory,
  can_trigger = Util.FalseFunc,
}
tangyuan:addSkill(fuyaoo)

Fk:loadTranslationTable{
  ["rfenghou__fuyaoo"] = "扶摇",
  [":rfenghou__fuyaoo"] = "锁定技，未回复过体力的角色在“蹈节”中视为“扶摇势力角色”。",
}


for i = 1, 10, 1 do
  Fk:loadTranslationTable{
    ["rfenghou"..i] = "封侯",
  }
end

local getAllCardNames = function(card_type, true_name)
  local all_names = {}
  local basics = {}
  local normalTricks = {}
  local delayedTricks = {}
  local equips = {}
  for _, card in ipairs(Fk.cards) do
      if card.package and not table.contains(Fk:currentRoom().disabled_packs, card.package.name) and not card.is_derived then
          if card.type == Card.TypeBasic then
              table.insertIfNeed(basics, true_name and card.trueName or card.name)
          elseif card.type == Card.TypeTrick and card.sub_type ~= Card.SubtypeDelayedTrick then
              table.insertIfNeed(normalTricks, true_name and card.trueName or card.name)
          elseif card.type == Card.TypeTrick and card.sub_type == Card.SubtypeDelayedTrick then
              table.insertIfNeed(delayedTricks, true_name and card.trueName or card.name)
          elseif card.type == Card.TypeEquip then
              table.insertIfNeed(equips, true_name and card.trueName or card.name)
          end
      end
  end
  if card_type:find("b") then
      table.insertTable(all_names, basics)
  end
  if card_type:find("t") then
      table.insertTable(all_names, normalTricks)
  end
  if card_type:find("d") then
      table.insertTable(all_names, delayedTricks)
  end
  if card_type:find("e") then
      table.insertTable(all_names, equips)
  end
  return all_names
end

local lvbao1 = General:new(extension, "rfenghou1__lvbao", "fuyao", 3, 3, General.Agender)--
lvbao1.hidden = true
Fk:loadTranslationTable{
  ["rfenghou1__lvbao"] = "铝",
  ["#rfenghou1__lvbao"] = "严于律众",
  ["designer:rfenghou1__lvbao"] = "汤圆",
}
local yiwangerping = fk.CreateTriggerSkill{
  name = "rfenghou__yiwangerping",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
      return player:hasSkill(self.name) and target == player and player.phase == Player.Draw
  end,
  on_cost = function (self, event, target, player, data)
      if player.room:askForSkillInvoke(player,self.name,nil,"#rfenghou__yiwangerping:::"..player:getHandcardNum()) then
          return true
      end
  end,
  on_use = function (self, event, target, player, data)
      local room = player.room
      for _, cp in ipairs(room:getOtherPlayers(player)) do
          local num = player:getHandcardNum()
          if num > cp:getHandcardNum() then
              cp:drawCards(num - cp:getHandcardNum(),self.name)
          elseif num < cp:getHandcardNum() then
              room:askForDiscard(cp, cp:getHandcardNum()-num, cp:getHandcardNum()-num, false, self.name, false)
          end
      end
      return true
  end,
}
lvbao1:addSkill(yiwangerping)
local gangjitielv = fk.CreateTriggerSkill{
  name = "rfenghou__gangjitielv",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
      if player:hasSkill(self) and (player == player.room.current or #player.room.logic:getActualDamageEvents(1, function(e)
          return e.data[1].to == player
      end) > 0) then
          local ids = {}
          local room = player.room
          for _, move in ipairs(data) do
              if move.toArea == Card.DiscardPile then
                  if move.moveReason == fk.ReasonDiscard and move.from and move.from ~= player.id then
                      for _, info in ipairs(move.moveInfo) do
                          if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) and
                          room:getCardArea(info.cardId) == Card.DiscardPile then
                              table.insertIfNeed(ids, info.cardId)
                          end
                      end
                  end
              else
                  if move.to ~= player.id and move.toArea == Card.PlayerHand and player.room:getPlayerById(move.to):getHandcardNum() > 0 then
                      self.cost_data = {value = 2, to = move.to}
                      return true
                  end
              end
          end
          ids = U.moveCardsHoldingAreaCheck(room, ids)
          if #ids > 0 then
              self.cost_data = {value = 1, cards = ids}
              return true
          end
      end
  end,
  on_cost = function (self, event, target, player, data)
      local room = player.room
      if self.cost_data.value == 1 then
          local use = U.askForUseRealCard(room, player, self.cost_data.cards, nil, self.name, "#rfenghou__gangjitielv-use", {
              bypass_times = true,
              extraUse = true,
              expand_pile = self.cost_data.cards,
          }, true, false)
          if use then
              self.cost_data = {value = 1,use = use}
              return true
          end
      else
          return room:getPlayerById(self.cost_data.to):getHandcardNum() > 0
      end
  end,
  on_use = function (self, event, target, player, data)
      local room = player.room
      if self.cost_data.value == 1 then
          room:useCard(self.cost_data.use)
      else
          local to = room:getPlayerById(self.cost_data.to)
          local id = room:askForCardChosen(player, to, { card_data = { { "$Hand", to:getCardIds(Player.Hand) }  } }, self.name)
          room:obtainCard(player, id, false, fk.ReasonPrey)
      end
  end,
}
lvbao1:addSkill(gangjitielv)
Fk:loadTranslationTable{
  ["rfenghou__yiwangerping"] = "一往而平",
  [":rfenghou__yiwangerping"] = "摸牌阶段，你可以改为令所有其他角色将手牌数调整至与你相同。",
  ["#rfenghou__yiwangerping"] = "是否发动 一往而平，将此阶段改成令所有其他角色将手牌数调整至与你相同（%arg）",
  ["rfenghou__gangjitielv"] = "钢纪铁律",
  [":rfenghou__gangjitielv"] = "你的回合内，其他角色弃置牌后，你使用其中一张。其他角色获得牌后，你观看其的手牌并获得其中一张。你受到伤害后，本回合内也可发动此技能。",
  ["#rfenghou__gangjitielv-use"] = "钢纪铁律：使用其中一张牌",
}

local lvbao2 = General:new(extension, "rfenghou2__lvbao", "fuyao", 3, 3, General.Agender)--
lvbao2.hidden = true
Fk:loadTranslationTable{
  ["rfenghou2__lvbao"] = "铝",
  ["#rfenghou2__lvbao"] = "",
  ["designer:rfenghou2__lvbao"] = "屑",
}
local shiren = fk.CreateTriggerSkill{
  name = "rfenghou__shiren",
  events = {fk.EventPhaseStart,fk.Damaged},
  can_trigger = function (self, event, target, player, data)
      if player:hasSkill(self.name) and target == player then
          return player.phase == Player.Start or event ~= fk.EventPhaseStart
      end
  end,
  dynamic_desc = function (self, player, lang)
      local arr = type(player:getMark("rfenghou__shiren")) == "table" and player:getMark("rfenghou__shiren") or {"eight_diagram","slash"}
      local str = "准备阶段，或你受到伤害后，你可以如【"
      str = str .. Fk:translate(arr[1],"zh_CN").."】般视为使用一张【"
      str = str .. Fk:translate(arr[2],"zh_CN").."】。以此判定失败后，你声明一张未声明过的即时牌替换第二个【】内，且均声明过后，第一个【】内改为“闪电”并重置声明牌。"
      return str
  end,
  on_cost = function (self, event, target, player, data)
      local room = player.room
      local arr = type(player:getMark("rfenghou__shiren")) == "table" and player:getMark("rfenghou__shiren") or {"eight_diagram","slash"}
      local use = U.askForUseVirtualCard(room,player,arr[2],nil,self.name,"#rfenghou__shiren:::"..arr[1]..":"..arr[2],true,true,true,true,nil,true)
      if use then
          self.cost_data = use
          return true
      end
  end,
  on_use = function (self, event, target, player, data)
      local room = player.room
      local arr = type(player:getMark("rfenghou__shiren")) == "table" and player:getMark("rfenghou__shiren") or {"eight_diagram","slash"}
      local judge = {
          who = player,
          reason = self.name,
          pattern = ".|.|heart,diamond",
      }
      if arr[1] == "lightning" then
          judge = {
              who = player,
              reason = self.name,
              pattern = ".|2~9|spade",
          }
      end
      room:judge(judge)
      local result = judge.card
      if arr[1] == "lightning" and result.suit == Card.Spade and result.number >= 2 and result.number <= 9 then
          room:damage{
              to = judge.who,
              damage = 3,
              damageType = fk.ThunderDamage,
              skillName = self.name,
          }
      end

      if Exppattern:Parse(judge.pattern):match(result) and not player.dead then
          room:useCard(self.cost_data)
      else
          local names = getAllCardNames("bt")
          for _, v in ipairs(player:getTableMark("rfenghou__shiren_cards")) do
              if table.contains(names,v) then
                  table.removeOne(names,v)
              end
          end
          table.removeOne(names,arr[2])
          if #names > 0 then
              local choice = player.room:askForChoice(player, names, self.name, "#rfenghou__shiren_choice")
              arr[2] = choice
              local marks = player:getTableMark("rfenghou__shiren_cards")
              table.insert(marks,choice)
              room:setPlayerMark(player,"rfenghou__shiren_cards",marks)
          end
          if #getAllCardNames("bt") == #player:getTableMark("rfenghou__shiren_cards") then
              arr[1] = "lightning"
              room:setPlayerMark(player,"rfenghou__shiren_cards",0)
          end
          room:setPlayerMark(player,"rfenghou__shiren",arr)
          room:setPlayerMark(player,"@rfenghou__shiren",table.concat(table.map(arr, Util.TranslateMapper)," "))
      end
  end,

  on_acquire = function (self, player, is_start)
      local room = player.room
      local arr = type(player:getMark("rfenghou__shiren")) == "table" and player:getMark("rfenghou__shiren") or {"eight_diagram","slash"}
      room:setPlayerMark(player,"rfenghou__shiren",arr)
      room:setPlayerMark(player,"@rfenghou__shiren",table.concat(table.map(arr, Util.TranslateMapper)," "))
  end,
  on_lose = function (self, player, is_death)
      player.room:setPlayerMark(player,"@rfenghou__shiren",0)
  end,
}
lvbao2:addSkill(shiren)
local tonghao = fk.CreateTriggerSkill{
  name = "rfenghou__tonghao",
  events = {fk.RoundStart},
  frequency = Skill.Limited,
  can_trigger = function (self, event, target, player, data)
      return player:hasSkill(self.name) and player:usedSkillTimes(self.name,Player.HistoryGame) == 0
  end,
  on_use = function (self, event, target, player, data)
      local room = player.room
      local generals, skillList = {}, {}
      local index = 1
      while #generals < 4 and index <= #room.general_pile do
          local g = room.general_pile[index]
          if Fk.generals[g].gender == General.Female then
              local skills = Fk.generals[g]:getSkillNameList(false)
              if #skills > 0 then
                  table.insert(generals, table.remove(room.general_pile, index))
                  table.insert(skillList, skills)
              else
                  index = index + 1
              end
          else
              index = index + 1
          end
      end
      local choice = {}
      if #generals == 0 then return false else choice = {skillList[1]} end
      if #generals > 0 then
          local result = player.room:askForCustomDialog(player, self.name,
          "packages/aaa_fenghou/qml/ChooseGeneralSkillsBox.qml", {
              generals, skillList, 2, 2, "#rfenghou__tonghao-choice", false
          })
          room:returnToGeneralPile(generals, "bottom")
          if result ~= "" then
              choice = json.decode(result)
          end
          room:setPlayerMark(player,self.name,choice)
          room:handleAddLoseSkills(player, table.concat(choice, "|"), nil)
      end
  end,

  refresh_events = {fk.AfterSkillEffect},
  can_refresh = function (self, event, target, player, data)
      return target == player and table.contains(player:getTableMark(self.name), data.name)
  end,
  on_refresh = function (self, event, target, player, data)
      local room = player.room
      room:removeTableMark(player, self.name, data.name)
      room:handleAddLoseSkills(player, "-"..data.name, nil, true, false)

      if #player:getTableMark(self.name) == 0 then
          if room:askForSkillInvoke(player,self.name,nil,"#rfenghou__tonghao-prompt:::"..data.name) then
              player:setSkillUseHistory(self.name,0,Player.HistoryGame)
          else
              room:handleAddLoseSkills(player, data.name, nil, true, false)
          end
      end
  end,
}
lvbao2:addSkill(tonghao)
Fk:loadTranslationTable{
  ["rfenghou__shiren"] = "势任",
  [":rfenghou__shiren"] = "准备阶段，或你受到伤害后，你可以如【八卦阵】般视为使用一张【杀】。以此判定失败后，你声明一张未声明过的即时牌替换第二个【】内，且均声明过后，第一个【】内改为“闪电”并重置声明牌。",
  ["#rfenghou__shiren"] = "是否发动 势任，如【%arg】般视为使用一张【%arg2】",
  ["#rfenghou__shiren_choice"] = "势任：声明一种牌名替换第二个【】内的牌名",
  ["@rfenghou__shiren"] = "势任",
  ["rfenghou__tonghao"] = "姛好",
  [":rfenghou__tonghao"] = "限定技，轮次开始时，你可以从四个女性武将牌中选择不同角色的两个技能获得之，并于发动后失去，均失去后，你复原“姛好”，或永久获得上次失去的技能。",
  ["#rfenghou__tonghao-choice"] = "是否发动 姛好？选择并获得两个技能",
  ["#rfenghou__tonghao-prompt"] = "复原 姛好 ？或点“取消”永久获得 %arg",
}

local lvbao3 = General:new(extension, "rfenghou3__lvbao", "fuyao", 3, 3, General.Agender)--
lvbao3.hidden = true
Fk:loadTranslationTable{
  ["rfenghou3__lvbao"] = "铝",
  ["#rfenghou3__lvbao"] = "氧化还原",
  ["designer:rfenghou3__lvbao"] = "独孤妙妙",
}
local danzhi = fk.CreateTriggerSkill{
  name = "rfenghou__danzhi",
  events = {fk.GameStart,"fk.GeneralAppeared"},
  can_trigger = function (self, event, target, player, data)
      return player:hasSkill(self.name) and (target == player or event == fk.GameStart)
  end,
  frequency = Skill.Compulsory,
  on_use = function (self, event, target, player, data)
      local room = player.room
      local choice = room:askForChoice(player,{"basic", "trick", "equip"},self.name,"#rfenghou__danzhi-prompt")
      local mark = {}
      if choice == "basic" then
          table.insert(mark,Card.TypeBasic)
      end
      if choice == "trick" then
          table.insert(mark,Card.TypeTrick)
      end
      if choice == "equip" then
          table.insert(mark,Card.TypeEquip)
      end
      room:setBanner("@[cardtypes]rfenghou__danzhi",mark)
      room:setPlayerMark(player,"@[cardtypes]rfenghou__danzhi",mark)
  end,
  on_acquire = function (self, player, is_start)
      local room = player.room
      room:setPlayerMark(player,"@[cardtypes]rfenghou__danzhi",room:getBanner("@[cardtypes]rfenghou__danzhi"))
  end,
  on_lose = function (self, player, is_death)
      player.room:setPlayerMark(player,"@[cardtypes]rfenghou__danzhi",0)
  end,
}
local danzhi_prohibit = fk.CreateProhibitSkill{
  name = "#rfenghou__danzhi_prohibit",
  prohibit_use = function(self, player, card)
      return player:hasSkill(self.name) and player:getMark("@[cardtypes]rfenghou__danzhi") ~= 0 and card and
      not table.contains(player:getTableMark("@[cardtypes]rfenghou__danzhi"), card.type)
  end,
}
danzhi:addRelatedSkill(danzhi_prohibit)
lvbao3:addSkill(danzhi)
local zhihuan = fk.CreateTriggerSkill{
  name = "rfenghou__zhihuan",
  events = {fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
      if player:hasSkill(self.name) and target ~= player then
          local room = player.room
          local skills = {}
          for _, skill in ipairs(target.player_skills) do
              if skill:isPlayerSkill(target) then
                  table.insert(skills, skill.name)
              end
          end
          return #room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
              local use = e.data[1]
              return use.from == player.id
          end, Player.HistoryTurn) > 0 and #room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
              local use = e.data[1]
              return use.from == target.id
          end, Player.HistoryTurn) > 0 and #skills > 0
      end
  end,
  on_cost = function (self, event, target, player, data)
      local room = player.room
      local skills = {}
      for _, skill in ipairs(player.player_skills) do
          if skill:isPlayerSkill(player) then
              table.insert(skills, skill.name)
          end
      end
      if #skills > 0 then
          table.insert(skills,"Cancel")
          local choice = room:askForChoice(player,skills,self.name,"#rfenghou__zhihuan-invoke::"..target.id,true)
          if choice ~= "Cancel" then
              self.cost_data = choice
              return true
          end
      end
  end,
  on_use = function (self, event, target, player, data)
      local room = player.room
      local skills = {}
      room:damage { from = player, to = target, damage = 1, skillName = self.name, damageType = fk.FireDamage }
      for _, skill in ipairs(target.player_skills) do
          if skill:isPlayerSkill(target) then
              table.insert(skills, skill.name)
          end
      end
      if #skills > 0 and not target.dead then
          local choice = room:askForChoice(player,skills,self.name,"#rfenghou__zhihuan-prompt::"..target.id..":"..self.cost_data,true)
          room:handleAddLoseSkills(player,"-"..self.cost_data,nil)
          room:handleAddLoseSkills(target,self.cost_data,nil)
          room:handleAddLoseSkills(target,"-"..choice,nil)
          room:handleAddLoseSkills(player,choice,nil)
      end
  end,
}
lvbao3:addSkill(zhihuan)
Fk:loadTranslationTable{
  ["rfenghou__danzhi"] = "单质",
  [":rfenghou__danzhi"] = "锁定技，游戏开始或你登场时，你选择一种类型的牌，拥有‘单质’的角色本局游戏只能使用该类型的牌。",
  ["#rfenghou__danzhi-prompt"] = "单质：声明一种类型，限制角色使用牌",
  ["@[cardtypes]rfenghou__danzhi"] = "单质",
  ["rfenghou__zhihuan"] = "置换",
  [":rfenghou__zhihuan"] = "其他角色的回合结束时，若你和其本回合都使用过牌，你可以对其造成1点火焰伤害，然后用一个技能交换其一个技能。",
  ["#rfenghou__zhihuan-invoke"] = "是否发动 置换，对 %dest 造成1点火焰伤害，并与其交换一个技能",
  ["#rfenghou__zhihuan-prompt"] = "置换：请选择要用 %arg 交换 %dest 的一个技能",
}

local lvbao4 = General:new(extension, "rfenghou4__lvbao", "fuyao", 3, 4, General.Agender)--
lvbao4.hidden = true
Fk:loadTranslationTable{
  ["rfenghou4__lvbao"] = "铝",
  ["#rfenghou4__lvbao"] = "颜色纯活",
  ["designer:rfenghou4__lvbao"] = "cyc",
}
Fk:addQmlMark{
  name = "rfenghou__xing",
  how_to_show = function(name, value)
      if type(value) == "table" then
          return tostring(#value)
      end
      return " "
  end,
  qml_path = "packages/aaa_fenghou/qml/rfenghou__xing"
}
local huo = fk.CreateActiveSkill{
  name = "rfenghou__huo",
  card_num = 0,
  target_num = 0,
  card_filter = Util.FalseFunc,
  target_filter = Util.FalseFunc,
  can_use = function (self, player, card, extra_data)
      return player:getMark("@rfenghou__huo") >= 10
  end,
  prompt = "#rfenghou__huo-prompt",
  on_use = function (self, room, effect)
      local player = room:getPlayerById(effect.from)
      room:removePlayerMark(player,"@rfenghou__huo",10)

      local mark = player:getTableMark("@[rfenghou__xing]")
      local generals = {}
      for _, general in pairs(Fk.generals) do
          if general.gender == General.Female and not general.hidden and not general.total_hidden then
              table.insert(generals, general.name)
          end
      end
      local loop = true
      local num = 0

      while loop and num < 10 do
          num = num + 1
          local general = table.random(generals)
          local all_choices = {general,{}}
          local forLoop = true
          for _, value in ipairs(mark) do
              if value[1] == general and forLoop then
                  forLoop = false
                  all_choices = value
              end
          end
          local choices  = {}
          for _, v in ipairs({"#rfenghou__huo1","#rfenghou__huo2","#rfenghou__huo3","#rfenghou__huo4"}) do
              if not table.contains(all_choices[2],v) then
                  table.insertIfNeed(choices,v)
              end
          end
          if #choices > 0 then
              loop = false
              local randomChoic = table.random(choices)
              table.insertIfNeed(all_choices[2],randomChoic)
              table.sort(all_choices[2],function (a, b)
                  local a_last = tonumber(a:sub(-1))
                  local b_last = tonumber(b:sub(-1))
                  return a_last < b_last
              end)
              local has = false
              for index, value in ipairs(mark) do
                  if value[1] == general and has == false then
                      has = true
                      mark[index] = all_choices
                  end
              end
              if has == false then
                  table.insert(mark,all_choices)
              end
              room:sendLog{
                  type = "#rfenghou__huo-gain-log",
                  from = player.id,
                  arg = self.name,
                  arg2 = general,
                  arg3 = randomChoic,
                  toast = true,
              }
              room:setPlayerMark(player,"@[rfenghou__xing]",mark)
              player:drawCards(#all_choices[2],self.name)
          end
      end
  end,
}
local huo_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou__huo_trigger",
  mute = true,
  events = {fk.AfterCardsMove,fk.Damaged},
  can_trigger = function(self, event, target, player, data)
      if player:hasSkill("rfenghou__huo") then
          if event == fk.AfterCardsMove then
              for _, move in ipairs(data) do
                  if move.toArea == Card.DiscardPile then
                      for _, info in ipairs(move.moveInfo) do
                          if Fk:getCardById(info.cardId).suit == Card.Heart then
                              return true
                          end
                      end
                  end
              end
          else
              return player == target and player:getMark("@rfenghou__huo") >= 10
          end
      end
  end,
  on_cost = function (self, event, target, player, data)
      if event == fk.AfterCardsMove then
          return true
      else
          if player.room:askForSkillInvoke(player,"rfenghou__huo",nil,"#rfenghou__huo-prompt") then
              return true
          end
      end
  end,
  on_trigger = function (self, event, target, player, data)
      local n = 0
      if event == fk.AfterCardsMove then
          for _, move in ipairs(data) do
              if move.toArea == Card.DiscardPile then
                  for _, info in ipairs(move.moveInfo) do
                      if Fk:getCardById(info.cardId).suit == Card.Heart then
                          n = n + 1
                      end
                  end
              end
          end
      else
          n = data.damage
      end
      for i = 1, n, 1 do
          if not player:hasSkill("rfenghou__huo") then return end
          self:doCost(event, target, player, data)
      end
  end,
  on_use = function (self, event, target, player, data)
      local room = player.room
      if event == fk.AfterCardsMove then
          room:notifySkillInvoked(player,"rfenghou__huo","masochism")
          room:addPlayerMark(player,"@rfenghou__huo",10)
      else
          room:notifySkillInvoked(player,"rfenghou__huo","special")
          room:removePlayerMark(player,"@rfenghou__huo",10)

          local mark = player:getTableMark("@[rfenghou__xing]")
          local generals = {}
          for _, general in pairs(Fk.generals) do
              if general.gender == General.Female and not general.hidden and not general.total_hidden then
                  table.insert(generals, general.name)
              end
          end
          local loop = true
          local num = 0

          while loop and num < 10 do
              num = num + 1
              local general = table.random(generals)
              local all_choices = {general,{}}
              local forLoop = true
              for _, value in ipairs(mark) do
                  if value[1] == general and forLoop then
                      forLoop = false
                      all_choices = value
                  end
              end
              local choices  = {}
              for _, v in ipairs({"#rfenghou__huo1","#rfenghou__huo2","#rfenghou__huo3","#rfenghou__huo4"}) do
                  if not table.contains(all_choices[2],v) then
                      table.insertIfNeed(choices,v)
                  end
              end
              if #choices > 0 then
                  loop = false
                  local randomChoic = table.random(choices)
                  table.insertIfNeed(all_choices[2],randomChoic)
                  table.sort(all_choices[2],function (a, b)
                      local a_last = tonumber(a:sub(-1))
                      local b_last = tonumber(b:sub(-1))
                      return a_last < b_last
                  end)
                  local has = false
                  for index, value in ipairs(mark) do
                      if value[1] == general and has == false then
                          has = true
                          mark[index] = all_choices
                      end
                  end
                  if has == false then
                      table.insert(mark,all_choices)
                  end
                  room:sendLog{
                      type = "#rfenghou__huo-gain-log",
                      from = player.id,
                      arg = "rfenghou__huo",
                      arg2 = general,
                      arg3 = randomChoic,
                      toast = true,
                  }
                  room:setPlayerMark(player,"@[rfenghou__xing]",mark)
                  player:drawCards(#all_choices[2],self.name)
              end
          end
      end
  end,
}
huo:addRelatedSkill(huo_trigger)
lvbao4:addSkill(huo)
local function hasFragment(player,str)
  local mark = player:getTableMark("@[rfenghou__xing]")
  if #mark == 0 then return false end
  for index, value in ipairs(mark) do
      if table.contains(value[2],str) then
          return true
      end
  end
end
local function hasAllFragment(player)
  local mark = player:getTableMark("@[rfenghou__xing]")
  if #mark == 0 then return false end
  for index, value in ipairs(mark) do
      if #value[2] >= 4 then
          return true
      end
  end
end
local xing = fk.CreateViewAsSkill{
  name = "rfenghou__xing",
  pattern = "savage_assault,drowning,peach,honey_trap",
  interaction = function ()
      local names, all_names = {}, {"honey_trap","peach","drowning","savage_assault"}
      local marks = {"#rfenghou__huo1","#rfenghou__huo2","#rfenghou__huo3","#rfenghou__huo4"}
      local used = Self:getTableMark("rfenghou__xing-turn")
      for index, name in ipairs(all_names) do
          local card = Fk:cloneCard(name)
          if not table.contains(used,name) and (hasFragment(Self,marks[index]) or hasAllFragment(Self)) and
          ((Fk.currentResponsePattern == nil and Self:canUse(card) and not Self:prohibitUse(card)) or
          (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card))) then
              table.insertIfNeed(names, card.name)
          end
      end
      if #names == 0 then return false end
      p(names)
      return UI.ComboBox { choices = names, all_choices = all_names }
  end,
  view_as = function (self, cards, player)
      if not self.interaction.data then return end
      local card = Fk:cloneCard(self.interaction.data)
      card.skillName = self.name
      return card
  end,
  before_use = function (self, player, use)
      local room = player.room
      local all_names = {["honey_trap"]="#rfenghou__huo1",["peach"]="#rfenghou__huo2",["drowning"]="#rfenghou__huo3",["savage_assault"]="#rfenghou__huo4"}
      local mark = player:getTableMark("@[rfenghou__xing]")
      local choices, trueChoices = {}, {}
      for _, value in ipairs(mark) do
          if #value[2] >= 4 or table.contains(value[2],all_names[use.card.name]) then
              trueChoices[Fk:translate(value[1],"zh_CN").."("..tostring(#value[2])..")"] = value[1]
              table.insert(choices,Fk:translate(value[1],"zh_CN").."("..tostring(#value[2])..")")
          end
      end
      if #choices > 0 then
          local choice = room:askForChoice(player,choices,self.name,"#rfenghou__xing-remove:::"..all_names[use.card.name])
          local trueChoice = trueChoices[choice]
          local removeIndex = {}
          for index, value in ipairs(mark) do
              if value[1] == trueChoice then
                  if #value[2] >= 4 then
                      if room:askForSkillInvoke(player,self.name,nil,"#rfenghou__xing-all:::"..value[1]..":"..use.card.name) then
                          value[2] = {}
                          table.insert(removeIndex,index)
                          use.extra_data = use.extra_data or {}
                          use.extra_data.rfenghou__xing = true
                          room:sendLog{
                              type = "#rfenghou__xing-all-log",
                              from = player.id,
                              arg = self.name,
                              arg2 = trueChoice,
                              toast = true,
                          }
                          break
                      end
                  end
                  room:sendLog{
                      type = "#rfenghou__xing-remove-log",
                      from = player.id,
                      arg = self.name,
                      arg2 = trueChoice,
                      arg3 = all_names[use.card.name],
                      toast = true,
                  }
                  table.removeOne(value[2],all_names[use.card.name])
              end
              if #value[2] == 0 then
                  table.insert(removeIndex,index)
              end
          end
          for _, index in ipairs(removeIndex) do
              table.remove(mark,index)
          end
          if #mark > 0 then
              room:setPlayerMark(player,"@[rfenghou__xing]",mark)
          else
              room:setPlayerMark(player,"@[rfenghou__xing]",0)
          end
      else
          return ""
      end
  end,
  after_use = function (self, player, use)
      local room = player.room
      local used = player:getTableMark("rfenghou__xing-turn")
      table.insert(used,use.card.name)
      room:setPlayerMark(player,"rfenghou__xing-turn",used)
  end,
  enabled_at_response = function (self, player, response)
      return not response
  end,
}
local xing_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou__xing_trigger",
  refresh_events = {fk.CardUsing},
  can_refresh = function (self, event, target, player, data)
      return target == player and data.extra_data and data.extra_data.rfenghou__xing
  end,
  on_refresh = function (self, event, target, player, data)
      data.additionalEffect = (data.additionalEffect or 0) + 3
  end,
}
xing:addRelatedSkill(xing_trigger)
lvbao4:addSkill(xing)
Fk:loadTranslationTable{
  ["rfenghou__huo"] = "活",
  [":rfenghou__huo"] = "一张<font color='red'>♥</font>进入弃牌堆后，你获得10点好感度。出牌阶段，或你受到1点伤害后，你可以消耗10好感度随机获取一块女性角色的武将碎片(4块合成完整武将，碎片从头、胸、腿、足中随机获得)，并摸该武将拼合进度张牌。",
  ["#rfenghou__huo-prompt"] = "是否发动 活，消耗10好感度随机获取一块女武将碎片",
  ["@rfenghou__huo"] = "好感度",
  ["@[rfenghou__xing]"] = "碎片背包",
  ["#rfenghou__huo1"] = "头部碎片",
  [":#rfenghou__huo1"] = "这是一块武将碎片……",
  ["#rfenghou__huo2"] = "胸部碎片",
  [":#rfenghou__huo2"] = "这是一块武将碎片……",
  ["#rfenghou__huo3"] = "腿部碎片",
  [":#rfenghou__huo3"] = "这是一块武将碎片……",
  ["#rfenghou__huo4"] = "足部碎片",
  [":#rfenghou__huo4"] = "这是一块武将碎片……",
  ["rfenghou__xing"] = "形",
  [":rfenghou__xing"] = "每回合每项限一次，你可以撕毁持有的一个武将的足部/腿部/胸部/头部/全部，视为使用一张【南蛮入侵】/【水淹七军】/【桃】/【美人计】/结算四次的一张上述牌。",
  ["#rfenghou__xing-remove"] = "形：请撕毁一个武将的 %arg",
  ["#rfenghou__xing-all"] = "形：你可以撕毁%arg的全部，另即将使用的%arg2结算4次",
  ["#rfenghou__huo-gain-log"] = "%from 发动〖%arg〗获得了 %arg2 的 <font color='#791cc0'>%arg3</font>",
  ["#rfenghou__xing-remove-log"] = "%from 发动〖%arg〗撕毁了 %arg2 的 <font color='#791cc0'>%arg3</font>",
  ["#rfenghou__xing-all-log"] = "%from 发动〖%arg〗撕毁了 %arg2 的 <font color='#791cc0'>全部碎片</font>",
}

local lvbao5 = General:new(extension, "rfenghou5__lvbao", "fuyao", 4, 4, General.Agender)--
lvbao5.hidden = true
Fk:loadTranslationTable{
  ["rfenghou5__lvbao"] = "铝",
  ["#rfenghou5__lvbao"] = "",
  ["designer:rfenghou5__lvbao"] = "桐葡草",
}
local kankan = fk.CreateActiveSkill{
  name = "rfenghou__kankan",
  can_use = function (self, player, card, extra_data)
      return player:usedSkillTimes(self.name,Player.HistoryPhase) == 0
  end,
  card_num = 1,
  card_filter = function (self, to_select, selected, player)
      local card = Fk:getCardById(to_select)
      return not card.multiple_targets and table.contains(player.player_cards[Player.Hand], to_select) and not table.contains({"jink","nullification"},card.trueName)
  end,
  target_num = 0,
  target_filter = Util.FalseFunc,
  on_use = function (self, room, effect)
      local player = room:getPlayerById(effect.from)
      local card = Fk:getCardById(effect.cards[1])
      local suit = card:getSuitString(true)
      local number = card:getNumberStr(card.number)
      room:sendLog{
          type = "#rfenghou__kankan-log",
          from = player.id,
          arg = self.name,
          arg2 = suit,
          arg3 = number,
          toast = true,
      }
      room:doIndicate(player.id, table.map(room.alive_players, Util.IdMapper))
      local targets = table.map(room:getOtherPlayers(player), Util.IdMapper)
      local req = Request:new(room:getOtherPlayers(player), "AskForUseActiveSkill")
      req.focus_text = self.name
      local extraData = {
          targets = table.map(room.alive_players, Util.IdMapper),
          num = 1,
          min_num = 1,
          pattern = "",
          skillName = self.name,
      }
      local data = { "choose_players_skill", "#rfenghou__kankan-prompt::"..player.id..":"..suit..":"..number, false, extraData, false }
      for _, p in ipairs(room:getOtherPlayers(player)) do
          req:setData(p, data)
          req:setDefaultReply(p, table.random(table.map(room.alive_players, Util.IdMapper)))
      end
      req:ask()
      for _, cp in ipairs(room:getOtherPlayers(player)) do
          local to
          if type(req:getResult(cp)) == "table" then
              to = req:getResult(cp).targets[1]
          else
              to = table.random(targets)
          end
          room:doIndicate(cp.id,{to})
          room:setPlayerMark(cp,"@[chara]rfenghou__kankan-phase",to)
      end

      local trueTarget = room:askForChoosePlayers(player,table.map(room.alive_players, Util.IdMapper),1,1,"#rfenghou__kankan-use:::"..card:toLogString())
      local use = {
          card = card,
          from = player.id,
          tos = table.map(trueTarget, function (id) return {id} end),
          extraUse = true,
      }
      room:useCard(use)

      local num = #table.filter(room.alive_players,function (cp)
          return cp:getMark("@[chara]rfenghou__kankan-phase") == trueTarget[1]
      end)
      for index, cp in ipairs(room.alive_players) do
          if cp:getMark("@[chara]rfenghou__kankan-phase") == trueTarget[1] then
              if num == 1 and cp:isWounded() then
                  room:recover({who = cp,num = 1,recoverBy = player,skillName = self.name})
              end
              if num == 2 then
                  cp:drawCards(1,self.name)
              end
              if num >= 3 and not cp:isNude() then
                  room:askForDiscard(cp, 1, 1, true, self.name, false)
                  player:setSkillUseHistory(self.name,0,Player.HistoryPhase)
              end
          end
      end
      for index, cp in ipairs(room.alive_players) do
          room:setPlayerMark(cp,"@[chara]rfenghou__kankan-phase",0)
      end
  end,
}
lvbao5:addSkill(kankan)
local wuwu = fk.CreateTriggerSkill{
  name = "rfenghou__wuwu",
  events = {fk.AfterCardsMove},
  can_trigger = function (self, event, target, player, data)
      if player:hasSkill(self.name) then
          local room = player.room
          local move_event = room.logic:getCurrentEvent()
          local parent_event = move_event.parent
          local card_ids = {}
          if parent_event ~= nil then
              if parent_event.event == GameEvent.UseCard or parent_event.event == GameEvent.RespondCard then
                  local parent_data = parent_event.data[1]
                  if parent_data.from == player.id and not parent_data.damageDealt then
                      card_ids = room:getSubcardsByRule(parent_data.card)
                  end
              elseif parent_event.event == GameEvent.Pindian then
                  local pindianData = parent_event.data[1]
                  if pindianData.from == player then
                      card_ids = room:getSubcardsByRule(pindianData.fromCard)
                  else
                      for toId, result in pairs(pindianData.results) do
                          if player.id == toId then
                              card_ids = room:getSubcardsByRule(result.toCard)
                              break
                          end
                      end
                  end
              end
          end
          for _, move in ipairs(data) do
              if move.toArea == Card.DiscardPile then
                  if move.from == player.id then
                      for _, info in ipairs(move.moveInfo) do
                          local card = Fk:getCardById(info.cardId)
                          if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) and
                          (card.type == Card.TypeEquip or card.is_damage_card) then
                              return true
                          end
                      end
                  elseif #card_ids > 0 then
                      for _, info in ipairs(move.moveInfo) do
                          local card = Fk:getCardById(info.cardId)
                          if info.fromArea == Card.Processing and table.contains(card_ids, info.cardId) and
                          (card.type == Card.TypeEquip or card.is_damage_card) then
                              return true
                          end
                      end
                  end
              end
          end
      end
  end,
  on_use = function (self, event, target, player, data)
      player:chat("呜呜")
      player:drawCards(1,self.name)
  end,
}
lvbao5:addSkill(wuwu)
Fk:loadTranslationTable{
  ["rfenghou__kankan"] = "看看",
  [":rfenghou__kankan"] = "出牌阶段限一次，你可以声明一张目标唯一的手牌的花色点数，令其他角色同时为你推荐目标，然后你使用此牌，且根据推荐该目标的角色数执行"..
  "<br>1名，其回复1点体力；<br>2名，其各摸一张牌；<br>3名及更多，其各弃置一张牌并重置此技能。",
  ["#rfenghou__kankan-log"] = "%from 发动了〖%arg〗，询问一张 %arg2%arg3 单目标牌的推荐目标",
  ["#rfenghou__kankan-prompt"] = "看看: %dest 询问你其使用一张 %arg%arg2 单目标牌的推荐目标",
  ["@[chara]rfenghou__kankan-phase"] = "推荐",
  ["#rfenghou__kankan-use"] = "看看：请选择你要使用 %arg 的目标",
  ["rfenghou__wuwu"] = "呜呜",
  [":rfenghou__wuwu"] = "你的伤害牌或装备牌进入弃牌堆时，若之未造成伤害，你可以呜呜并摸一张牌。",
}

local lvbao6 = General:new(extension, "rfenghou6__lvbao", "fuyao", 4, 4, General.Agender)--
Fk:loadTranslationTable{
  ["rfenghou6__lvbao"] = "铝",
  ["#rfenghou6__lvbao"] = "",
  ["designer:rfenghou6__lvbao"] = "ッ老酒馆的猫",
}
local baihuaqifang = fk.CreateTriggerSkill{
  name = "rfenghou__baihuaqifang",
  refresh_events = {"fk.GeneralAppeared"},
  can_refresh = function (self, event, target, player, data)
      local tName = Fk.generals[player.general].trueName
      local ret = Fk.same_generals[tName] or {}
      if data.extra_data and data.extra_data.rfenghou_baihuaqifang then return end
      return player:hasSkill(self.name) and player == target and #table.filter(ret, function(g)
          return g ~= player.general and Fk.generals[g] ~= nil
      end) > 0
  end,
  on_refresh = function (self, event, target, player, data)
      local room = player.room
      room:notifySkillInvoked(player,self.name,"special")
      local tName = Fk.generals[player.general].trueName
      local ret = Fk.same_generals[tName] or {}
      local sameGenerals = table.filter(ret, function(g)
          return g ~= player.general and Fk.generals[g] ~= nil
      end)
      local general = room:askForGeneral(player, table.random(sameGenerals, 4), 1, true)
      room:findGeneral(general)
      room:changeHero(player, general, false, false, true, true)

      local event_data = {["m"] = general}
      local deputy = Fk.generals[player.deputyGeneral]
      if deputy then
          room:sendLog{ type = "#RevealGeneral", from = player.id, arg =  "deputyGeneral", arg2 = deputy.name }
          event_data["d"] = deputy.name
      end
      event_data.extra_data = {}
      event_data.extra_data.rfenghou_baihuaqifang = true
      room.logic:trigger("fk.GeneralAppeared", player, event_data)
  end,
}
baihuaqifang.isHiddenSkill = true
lvbao6:addSkill(baihuaqifang)
Fk:loadTranslationTable{
  ["rfenghou__baihuaqifang"] = "百花齐放",
  [":rfenghou__baihuaqifang"] = "隐匿。你登场时，从四张同名武将中选择一张登场。",
}

local lvbao7 = General:new(extension, "rfenghou7__lvbao", "fuyao", 4, 4, General.Agender)--
lvbao7.hidden = true
Fk:loadTranslationTable{
  ["rfenghou7__lvbao"] = "铝",
  ["#rfenghou7__lvbao"] = "",
  ["designer:rfenghou7__lvbao"] = "钇宝",
}
local xinjiangyugao = fk.CreateTriggerSkill{
  name = "rfenghou__xinjiangyugao",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
      return player:hasSkill(self.name) and target.phase == Player.Start and target == player
  end,
  on_use = function (self, event, target, player, data)
      local room = player.room
      local record = room:getTag("rfenghou__xinjiangyugao_recod")
      if record == nil then
          record = {}
          for packageName, package in pairs(Fk.packages) do
              if package.extensionName == "ysch_Al" then
                  for _, general in ipairs(package.generals) do
                      if not Fk.generals[general.name].hidden and not Fk.generals[general.name].total_hidden then
                          table.insert(record, general.name)
                      end
                  end
              end
          end
          room:setTag("rfenghou__xinjiangyugao_recod", record)
      end
      if #record == 0 then return end
      local generals = table.random(record,5)
      room:setPlayerMark(player,"@&rfenghou__xinjiangyugao-phase",generals)
      room:sendLog({
          type = "#rfenghou__xinjiangyugao_gengral-log",
          from = player.id,
          arg = self.name,
          arg2 = table.concat(table.map(generals,Util.TranslateMapper),"、"),
          toast = true,
      })
      local result = room:askForCustomDialog(player, self.name,
      "packages/utility/qml/ChooseGeneralsAndChoiceBox.qml", {
          generals,
          {"OK"},
          "#rfenghou__xinjiangyugao_general",
          {},
          1,
          1
      })
      if result ~= "" then
          local reply = json.decode(result)
          local general = reply.cards[1]
          local choices = room:askForChoices(player,{"#rfenghou__xinjiangyugao1","#rfenghou__xinjiangyugao2","#rfenghou__xinjiangyugao3",
          "#rfenghou__xinjiangyugao4","#rfenghou__xinjiangyugao5","#rfenghou__xinjiangyugao6"},0,3,self.name,"#rfenghou__xinjiangyugao_choice:::"..general,false)
          local prompt = "#rfenghou__xinjiangyugao-prompt2::"..target.id
          if #choices > 0 then
              player:drawCards(#choices,self.name)
              room:sendLog({
                  type = "#rfenghou__xinjiangyugao_choice-log",
                  from = player.id,
                  arg = table.concat(table.map(choices,Util.TranslateMapper),"、"),
                  toast = true,
              })
              prompt = "#rfenghou__xinjiangyugao-prompt::"..target.id..":"..table.concat(table.map(choices,Util.TranslateMapper))
          end

          local req = Request:new(room:getOtherPlayers(player), "AskForChoice")
          req.focus_text = self.name
          req.receive_decode = false
          for _, cp in ipairs(room:getOtherPlayers(player)) do
              req:setData(cp, {generals, generals, self.name, prompt})
              req:setDefaultReply(cp, table.random(generals))
          end
          req:ask()
          local trueP, falseP = {}, {}
          for _, p in ipairs(room:getOtherPlayers(player)) do
              if req:getResult(p) == general then
                  table.insert(trueP,p)
              else
                  table.insert(falseP,p)
              end
              room:sendLog{
                  type = "#Choice",
                  from = p.id,
                  arg = req:getResult(p),
                  toast = true,
              }
          end
          for _, cp in ipairs(trueP) do
              if not (cp.dead or player:isNude() or cp == player) then
                  local card = room:askForCard(player, 1, 1, false, self.name, false, nil, "#rfenghou__xinjiangyugao-give::"..cp.id)
                  room:moveCardTo(card, Card.PlayerHand, cp, fk.ReasonGive, self.name, nil, false, player.id)
              end
          end
          for _, cp in ipairs(falseP) do
              room:loseHp(cp,1,self.name)
          end
          if #falseP == 0 then
              local skills = Fk.generals[general]:getSkillNameList(true)
              room:handleAddLoseSkills(player,skills)
          end
      end
      room:setPlayerMark(player,"@&rfenghou__xinjiangyugao-phase",0)
  end,
}
lvbao7:addSkill(xinjiangyugao)
Fk:loadTranslationTable{
  ["rfenghou__xinjiangyugao"] = "新将预告",
  [":rfenghou__xinjiangyugao"] = "准备阶段，你可以展示五个“妍设长河”的武将并秘密选择其中一个，声明其至多三个特征并摸等量张牌。然后其他角色同时猜测你声明的武将，你交给猜对者一张手牌，猜错者失去1点体力。若均猜对，你获得该武将的技能。"..
  "<br>（特征包括：神人，过牌，弱将，辅助，输出，涩涩）",
  ["#rfenghou__xinjiangyugao1"] = "神人",
  ["#rfenghou__xinjiangyugao2"] = "过牌",
  ["#rfenghou__xinjiangyugao3"] = "弱势",
  ["#rfenghou__xinjiangyugao4"] = "辅助",
  ["#rfenghou__xinjiangyugao5"] = "输出",
  ["#rfenghou__xinjiangyugao6"] = "涩涩",
  ["@&rfenghou__xinjiangyugao-phase"] = "新将预告",
  ["#rfenghou__xinjiangyugao_general"] = "新将预告：秘密选择一张武将牌",
  ["#rfenghou__xinjiangyugao_choice"] = "新将预告：请你声明 %arg 的至多三个特征并摸等量张牌",
  ["#rfenghou__xinjiangyugao_gengral-log"] = "%from 发动了〖%arg〗，展示了 %arg2",
  ["#rfenghou__xinjiangyugao_choice-log"] = "%from 声明选择武将有以下特征：%arg",
  ["#rfenghou__xinjiangyugao-prompt"] = "新将预告：%dest 声明选择武将有以下特征：%arg。请猜测其选择的武将",
  ["#rfenghou__xinjiangyugao-prompt2"] = "新将预告：%dest没有声明武将特征，请猜测其选择的武将",
  ["#rfenghou__xinjiangyugao-give"] = "新将预告：%dest 猜对了你选择的武将，交给其一张手牌",
}

local lvbao8 = General:new(extension, "rfenghou8__lvbao", "fuyao", 3, 5, General.Agender)--
lvbao8.hidden = true
Fk:loadTranslationTable{
  ["rfenghou8__lvbao"] = "铝",
  ["#rfenghou8__lvbao"] = "",
  ["designer:rfenghou8__lvbao"] = "阳纸",
}
local TAG_PATTERN = "<[^>]+>"
-- 分割字符串为文本块和标签块
local function split_text_and_tags(s)
  local parts = {}
  local last_end = 1

  -- 遍历所有标签匹配项
  for tag_start, tag_end in s:gmatch("()"..TAG_PATTERN.."()") do
      -- 提取标签前的文本
      if tag_start > last_end then
          local text = s:sub(last_end, tag_start - 1)
          table.insert(parts, {type="text", content=text})
      end
      -- 提取标签
      local tag = s:sub(tag_start, tag_end - 1)
      table.insert(parts, {type="tag", content=tag})
      last_end = tag_end
  end

  -- 处理末尾的剩余文本
  if last_end <= #s then
      local text = s:sub(last_end)
      table.insert(parts, {type="text", content=text})
  end

  return parts
end
-- UTF-8 安全分割函数
local function utf8_split(s)
  local chars = {}
  local i = 1
  while i <= #s do
      local c = string.byte(s, i)
      local shift = 1
      if c >= 0xF0 then  -- 4字节字符
          shift = 4
      elseif c >= 0xE0 then  -- 3字节字符（如中文）
          shift = 3
      elseif c >= 0xC0 then  -- 2字节字符
          shift = 2
      end
      table.insert(chars, string.sub(s, i, i + shift - 1))
      i = i + shift
  end
  return chars
end
-- Fisher-Yates 洗牌算法
local function shuffle(t)
  for i = #t, 2, -1 do
      local j = math.random(i)
      t[i], t[j] = t[j], t[i]
  end
  return t
end
local function shuffle_with_keep_tags(s)
  local parts = split_text_and_tags(s)
  local result = {}

  for _, part in ipairs(parts) do
      if part.type == "text" then
          -- 分割并打乱文本部分
          local chars = utf8_split(part.content)
          --[[if #result > 1 then
              table.insert(result, math.random(#result), table.concat(shuffle(chars)))
          else]]--
              table.insert(result, table.concat(shuffle(chars)))
          --end
      else
          -- 直接保留标签
          table.insert(result, part.content)
      end
  end

  return table.concat(result)
end
local xinmashikong = fk.CreateTriggerSkill{
  name = "rfenghou__xinmashikong",
  events = {fk.GameStart},
  can_trigger = function (self, event, target, player, data)
      return player:hasSkill(self.name)
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
      local room = player.room
      for _, cp in ipairs(room:getOtherPlayers(player)) do
          local translate, skills = cp:getTableMark("rfenghou__xinmashikong_translate"), {}
          for _, skill in ipairs(cp.player_skills) do
              local name = skill.name
              local str = Fk:translate(":"..name,"zh_CN")
              if str and str ~= "" and not skill:isEquipmentSkill(cp) then
                  str = shuffle_with_keep_tags(str)
                  str = "<b>" .. Fk:translate(name,"zh_CN") .. "</b>:" .. str
                  --Fk.translations["zh_CN"][":"..name] = str
                  table.insertIfNeed(translate,str)
                  table.insertIfNeed(skills,name)
              end
          end
          if #skills > 0 then
              room:handleAddLoseSkills(cp,"-"..table.concat(skills,"|-"),nil,false,true)
          end
          room:handleAddLoseSkills(cp,"rfenghou__xinmashikong_translate",nil,false,true)
          if #translate > 0 then
              table.insert(translate,1,"此武将技能描述已被"..Fk:translate(player.general,"zh_CN").."打乱")
              room:setPlayerMark(cp,"rfenghou__xinmashikong_translate",translate)
          end
          if #skills > 0 then
              room:handleAddLoseSkills(cp,table.concat(skills,"|"),nil,false,true)
          end
      end
  end,
  on_acquire = function (self, player, is_start)
      local room = player.room
      for _, cp in ipairs(room:getOtherPlayers(player)) do
          local translate, skills = cp:getTableMark("rfenghou__xinmashikong_translate"), {}
          for _, skill in ipairs(cp.player_skills) do
              local name = skill.name
              local str = Fk:translate(":"..name,"zh_CN")
              if str and str ~= "" and not skill:isEquipmentSkill(cp) then
                  str = shuffle_with_keep_tags(str)
                  str = "<b>" .. Fk:translate(name,"zh_CN") .. "</b>:" .. str
                  --Fk.translations["zh_CN"][":"..name] = str
                  table.insertIfNeed(translate,str)
                  table.insertIfNeed(skills,name)
              end
          end
          if #skills > 0 then
              room:handleAddLoseSkills(cp,"-"..table.concat(skills,"|-"),nil,false,true)
          end
          room:handleAddLoseSkills(cp,"rfenghou__xinmashikong_translate",nil,false,true)
          if #translate > 0 then
              table.insert(translate,1,"该角色技能描述已被"..Fk:translate(player.general,"zh_CN").."打乱")
              room:setPlayerMark(cp,"rfenghou__xinmashikong_translate",translate)
          end
          if #skills > 0 then
              room:handleAddLoseSkills(cp,table.concat(skills,"|"),nil,false,true)
          end
      end
  end,
}
Fk:addQmlMark{
  name = "xinmashikong",
  how_to_show = function(name, value)
      return " "
  end,
  qml_path = function(name, value, p)
      if Self:isBuddy(p) then
        return "packages/utility/qml/DetailBox"
      end
      return ""
  end,
}
local xinmashikong_translate = fk.CreateActiveSkill{
  name = "rfenghou__xinmashikong_translate",
  dynamic_desc = function (self, player, lang)
      local str = "<br>"
      if type(player:getMark(self.name)) == "table" then
          str = str .. table.concat(player:getMark(self.name),"<br>")
      end
      if #player:getCardIds("ej") > 0 then
          local equips = {}
          for _, id in ipairs(player:getCardIds("ej")) do
              local card = Fk:getCardById(id)
              table.insert(equips,card.name)
          end
          if #equips > 0 then
              str = str .. "<br>--------------------<br>"
              str = str .. table.concat(table.map(equips,function (equip)
                 return "<b>"..Fk:translate(equip,"zh_CN").."</b>："..Fk:translate(":"..equip,"zh_CN")
              end),"<br>--------------------<br>")
          end
      end
      for i = 1, 200, 1 do
          str = str .. "<br>"
      end
      return str
  end,
  mute = true,
  card_num = 1,
  target_num = 1,
  card_filter = function(self, to_select, selected)
      return #selected == 0
    end,
  target_filter = function(self, to_select, selected)
      return #selected == 0 and to_select ~= Self.id and Fk:currentRoom():getPlayerById(to_select):hasSkill(xinmashikong) and
      not table.contains(Self:getTableMark("rfenghou__xinmashikong_targets-phase"), to_select)
  end,
  can_use = function(self, player)
      local targetRecorded = player:getTableMark("rfenghou__xinmashikong_targets-phase")
      return table.find(Fk:currentRoom().alive_players, function(p)
        return p ~= player and p:hasSkill(xinmashikong, true) and not table.contains(targetRecorded, p.id)
      end)
  end,
  on_use = function(self, room, effect)
      local player = room:getPlayerById(effect.from)
      local target = room:getPlayerById(effect.tos[1])
      room:notifySkillInvoked(target,"rfenghou__xinmashikong","special")
      room:addTableMarkIfNeed(player, "rfenghou__xinmashikong_targets-phase", target.id)
      local id = effect.cards[1]
      room:obtainCard(target.id, id, false, fk.ReasonGive, player.id)

      local mark = player:getTableMark("@[xinmashikong]rfenghou__xinmashikong-phase")
      for _, cp in ipairs(room.players) do
          table.insertIfNeed(mark,cp.general)
          for _, skill in ipairs(cp.player_skills) do
              local name = skill.name
              local str = Fk:translate(":"..name,"zh_CN")
              if str and str ~= "" and not skill:isEquipmentSkill(cp) then
                  table.insertIfNeed(mark,name)
              end
          end
          table.insert(mark,"==========")
      end
      room:setPlayerMark(player,"@[xinmashikong]rfenghou__xinmashikong-phase",mark)
  end,
}
Fk:addSkill(xinmashikong_translate)
lvbao8:addSkill(xinmashikong)
--[[local xuyaozhiliao_events = {}
for i = 1, 105, 1 do
  table.insert(xuyaozhiliao_events,i)
end]]--
local xuyaozhiliao = fk.CreateTriggerSkill{
  name = "rfenghou__xuyaozhiliao",
  dynamic_desc = function (self, player, lang)
      return "你的武将牌始终播放“救我...”。非当前回合角色回复体力时，"..tostring(math.min(100,30 + player:getLostHp()*10)).."%的概率转移至你（你每损失1点体力，概率增加10%）。"
  end,
  anim_type = "support",
  events = {fk.PreHpRecover},
  can_trigger = function(self, event, target, player, data)
      return player:hasSkill(self) and (math.random() < (0.3 + player:getLostHp()*0.1)) and target ~= player and target ~= player.room.current
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
      if player:isWounded() then
          local num = math.min(player:getLostHp(),data.num)
          player.room:recover{
              who = player,
              num = num,
              skillName = self.name,
              recoverBy = target,
          }
      end
      return true
  end,
  refresh_events = {fk.BeforeCardsMove,fk.BeforeHpChanged},
  can_refresh = function (self, event, target, player, data)
      return player:hasSkill(self.name)
  end,
  on_refresh = function (self, event, target, player, data)
      --player.dying = true
      player.room:setEmotion(player, "./packages/aaa_fenghou/image/anim/death")
  end,
}
lvbao8:addSkill(xuyaozhiliao)
local buhuijueqing = fk.CreateTriggerSkill{
  name = "rfenghou__buhuijueqing",
  events = {fk.DamageCaused},
  can_trigger = function (self, event, target, player, data)
      return player:hasSkill(self.name) and target == player
  end,
  on_cost = function (self, event, target, player, data)
      if player.room:askForSkillInvoke(player,self.name,nil,"#rfenghou__buhuijueqing::"..data.to.id) then
          return true
      end
  end,
  on_use = function (self, event, target, player, data)
      local room = player.room
      room:loseHp(player, 1, self.name)
      if player.hp > data.to.hp then
          data.to:drawCards(1,self.name)
      elseif data.to.hp > player.hp then
          player:drawCards(1,self.name)
      else
          player:drawCards(1,self.name)
          data.to:drawCards(1,self.name)
      end
  end,
}
lvbao8:addSkill(buhuijueqing)
Fk:loadTranslationTable{
  ["rfenghou__xinmashikong"] = "心码失控",
  [":rfenghou__xinmashikong"] = "游戏开始时或你获得此技能时，你打乱其他角色的技能描述。每名角色出牌阶段限一次，其可以交给你一张手牌，令其本回合可以观看所有角色技能的原描述。",
  ["@[xinmashikong]rfenghou__xinmashikong-phase"] = "正常描述",
  ["rfenghou__xuyaozhiliao"] = "需要治疗",
  [":rfenghou__xuyaozhiliao"] = "你的武将牌始终播放“救我...”。非当前回合角色回复体力时，30%的概率转移至你（你每损失1点体力，概率增加10%）。",
  ["rfenghou__xinmashikong_translate"] = "乱码描述",
  [":rfenghou__xinmashikong_translate"] = "",
  ["rfenghou__buhuijueqing"] = "不会绝情",
  [":rfenghou__buhuijueqing"] = "你造成伤害时，可以失去1点体力，令你与受伤角色体力值较少者摸一张牌。",
  ["#rfenghou__buhuijueqing"] = "是否发动 不会绝情，失去1点体力，令你与 %dest 体力值较少者摸一张牌",
}

local lvbao9 = General:new(extension, "rfenghou9__lvbao", "fuyao", 4, 4, General.Agender)--
lvbao9.hidden = true
Fk:loadTranslationTable{
  ["rfenghou9__lvbao"] = "铝",
  ["#rfenghou9__lvbao"] = "心缕怎决",
  ["designer:rfenghou9__lvbao"] = "Sachiko",
}
local qingxinlengyi = fk.CreateTriggerSkill{
  name = "rfenghou__qingxinlengyi",
  events = {fk.CardEffectCancelledOut,fk.DamageFinished},
  can_trigger = function(self, event, target, player, data)
      if player:hasSkill(self) then
          if event == fk.CardEffectCancelledOut then
              return data.from and data.from == player.id
          else
              return not data.dealtRecorderId and data.to == player
          end
      end
  end,
  frequency = Skill.Compulsory,
  on_use = function (self, event, target, player, data)
      local room = player.room
      if player.hp > player:getHandcardNum() then
          player:drawCards(1,self.name)
      elseif player:getHandcardNum() > player.hp and player:isWounded() then
          room:recover({
              who = player,
              num = 1,
              recoverBy = player,
              skillName = self.name,
          })
      else
          room:recastCard(player:getCardIds("h"),player,self.name)
      end
  end,
}
lvbao9:addSkill(qingxinlengyi)
local jiuyirushuang = fk.CreateTriggerSkill{
  name = "rfenghou__jiuyirushuang",
  events = {fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self.name) then
      return #player.room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
          for _, move in ipairs(e.data) do
              if move.to == player.id and move.toArea == Card.PlayerHand then
                return true
              end
              if move.from == player.id then
                  for _, info in ipairs(move.moveInfo) do
                      if info.fromArea == Card.PlayerHand then
                          return true
                      end
                  end
              end
          end
      end, Player.HistoryTurn) > 0 and #player.room.logic:getEventsOfScope(GameEvent.ChangeHp, 1, function (e)
          return e.data[1] == player
      end, Player.HistoryTurn) > 0
    end
  end,
  frequency = Skill.Compulsory,
  on_use = function (self, event, target, player, data)
      local room = player.room
      local suits, used = {}, {}
      for _, id in ipairs(Fk:currentRoom():getBanner("@$CenterArea")) do
          table.insertIfNeed(suits, Fk:getCardById(id).suit)
      end
      table.removeOne(suits, Card.NoSuit)
      local gainCards = {}
      while #used < #suits do
          local lose, gain = player:getTableMark("rfenghou__jiuyirushuang_lose"), player:getTableMark("rfenghou__jiuyirushuang_gain")
          lose = table.filter(lose,function (id)
              local card = Fk:getCardById(id)
              return (card.type == Card.TypeBasic or card:isCommonTrick()) and not table.contains(used,card.suit)
          end)
          gain = table.filter(gain,function (id)
              local card = Fk:getCardById(id)
              return (card.type == Card.TypeBasic or card:isCommonTrick()) and not table.contains(used,card.suit)
          end)
          local marks = {}
          for _, id in ipairs(lose) do
              if not table.contains(gain,id) and not table.contains(used,Fk:getCardById(id).suit) then
                  table.insert(marks,id)
              end
          end
          if #marks > 0 then
              local use = U.askForUseRealCard(room,player,marks,nil,self.name,"#rfenghou__jiuyirushuang-use",{
                  bypass_times = true,
                  extraUse = true,
                  expand_pile = marks,
              },false,false)
              if use then
                  table.insert(gainCards,use.card.id)
                  table.insert(used,use.card.suit)
              else
                  break
              end
          else
              break
          end
      end

      local cancelled = {}
      player.room.logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
        local use = e.data[1]
        if use and (use.cardsResponded and #use.cardsResponded > 0) and table.contains(gainCards,use.card.id) then
          table.insertIfNeed(cancelled, use.card.id)
        end
      end, Player.HistoryTurn)
      gainCards = table.filter(gainCards,function (id)
          return not table.contains(cancelled,id)
      end)
      if #gainCards > 0 then
          room:obtainCard(player,gainCards,true)
      end
      if #cancelled > 0 then
          for i = 1, #cancelled, 1 do
              room:damage{
                  from = player,
                  to = player,
                  damage = 1,
                  damageType = fk.IceDamage,
                  skillName = self.name,
              }
          end
      end
  end,

  refresh_events = {fk.AfterCardsMove},
  can_refresh = function (self, event, target, player, data)
      local mark = player:getTableMark("rfenghou__jiuyirushuang_lose")
      for _, move in ipairs(data) do
          if move.from == player.id and
          not (move.to == player.id and (move.toArea == Card.PlayerHand or move.toArea == Card.PlayerEquip)) then
              for _, info in ipairs(move.moveInfo) do
                  if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                      return true
                  end
              end
          end
          if move.to == player.id and move.toArea == Card.PlayerHand then
              for _, info in ipairs(move.moveInfo) do
                  if table.contains(mark,info.cardId) then
                      return true
                  end
              end
          end
      end
  end,
  on_refresh = function (self, event, target, player, data)
      local room = player.room
      local lose, gain = player:getTableMark("rfenghou__jiuyirushuang_lose"), player:getTableMark("rfenghou__jiuyirushuang_gain")
      for _, move in ipairs(data) do
          if move.from == player.id and
          not (move.to == player.id and (move.toArea == Card.PlayerHand or move.toArea == Card.PlayerEquip)) then
              for _, info in ipairs(move.moveInfo) do
                  if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                      table.insertIfNeed(lose, info.cardId)
                  end
              end
          end
          if move.to == player.id and move.toArea == Card.PlayerHand then
              for _, info in ipairs(move.moveInfo) do
                  if table.contains(lose,info.cardId) then
                      table.insertIfNeed(gain, info.cardId)
                  end
              end
          end
      end
      lose = table.filter(lose,function (id)
          local card = Fk:getCardById(id)
          return card.type == Card.TypeBasic or card:isCommonTrick()
      end)
      gain = table.filter(gain,function (id)
          local card = Fk:getCardById(id)
          return card.type == Card.TypeBasic or card:isCommonTrick()
      end)
      room:setPlayerMark(player,"rfenghou__jiuyirushuang_lose",lose)
      room:setPlayerMark(player,"rfenghou__jiuyirushuang_gain",gain)

      local marks = {}
      for _, id in ipairs(lose) do
          if not table.contains(gain,id) then
              table.insert(marks,id)
          end
      end
      if player:hasSkill(self.name) and #marks > 0 then
          room:setPlayerMark(player,"@$rfenghou__jiuyirushuang",marks)
      else
          room:setPlayerMark(player,"@$rfenghou__jiuyirushuang",0)
      end
  end,
  on_acquire = function (self, player, is_start)
      local room = player.room
      local lose, gain = player:getTableMark("rfenghou__jiuyirushuang_lose"), player:getTableMark("rfenghou__jiuyirushuang_gain")
      local marks = {}
      for _, id in ipairs(lose) do
          if not table.contains(gain,id) then
              table.insert(marks,id)
          end
      end
      if player:hasSkill(self.name) and #marks > 0 then
          room:setPlayerMark(player,"@$rfenghou__jiuyirushuang",marks)
      else
          room:setPlayerMark(player,"@$rfenghou__jiuyirushuang",0)
      end
  end,
  on_lose = function (self, player, is_death)
      player.room:setPlayerMark(player,"@$rfenghou__jiuyirushuang",0)
  end,
}
jiuyirushuang.CenterArea = true
lvbao9:addSkill(jiuyirushuang)
Fk:loadTranslationTable{
  ["rfenghou__qingxinlengyi"] = "清心冷意",
  [":rfenghou__qingxinlengyi"] = "锁定技，当你使用的牌被抵消，或你受到的伤害被防止后，你将手牌数和体力值中更少的一项向另一项调整1，若无事发生，则你重铸所有手牌。",
  ["rfenghou__jiuyirushuang"] = "旧忆如霜",
  [":rfenghou__jiuyirushuang"] = "锁定技，你的手牌数和体力值均发生过变化的回合结束时，你视为使用你已失去且未再次得到过的X张花色各不同的即时牌（X为中央区花色数），均结算后，其中每有一张牌：未被抵消，你便获得之对应的实体牌；没有生效，你便依次对自己造成1点冰冻伤害。",
  ["@$rfenghou__jiuyirushuang"] = "旧忆如霜",
  ["#rfenghou__jiuyirushuang-use"] = "旧忆如霜：请使用一张牌",
}

local lvbao10 = General:new(extension, "rfenghou10__lvbao", "fuyao", 3, 3, General.Agender)--
lvbao10.hidden = true
Fk:loadTranslationTable{
  ["rfenghou10__lvbao"] = "铝",
  ["#rfenghou10__lvbao"] = "",
  ["designer:rfenghou10__lvbao"] = "ッ老酒馆的猫",
}
Fk:addQmlMark{
  name = "rfenghou__yisiquanhuang",
  qml_path = function(name, value, p)
      if Self == p then
          return "packages/aaa_fenghou/qml/rfenghou__yisiquanhuang"
      end
      return ""
  end,
  how_to_show = function(name, value, p)
    return " "
  end,
}
local yisiquanhuang = fk.CreateTriggerSkill{
  name = "rfenghou__yisiquanhuang",
  events = {fk.AfterCardsMove},
  can_trigger = function (self, event, target, player, data)
      if player:hasSkill(self.name) then
          for _, move in ipairs(data) do
              if move.from == player.id then
                  if move.extra_data then
                      if move.extra_data.rfenghou__yisiquanhuangRed and not table.find(player:getCardIds("h"), function(id) return Fk:getCardById(id).color == Card.Red end) then
                          return true
                      end
                      if move.extra_data.rfenghou__yisiquanhuangBlack and not table.find(player:getCardIds("h"), function(id) return Fk:getCardById(id).color == Card.Black end) then
                          return true
                      end
                  end
              end
          end
      end
  end,
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  on_use = function (self, event, target, player, data)
      local room = player.room
      local colors = {}
      for _, move in ipairs(data) do
          if move.from == player.id then
              if move.extra_data then
                  if move.extra_data.rfenghou__yisiquanhuangRed and not table.find(player:getCardIds("h"), function(id) return Fk:getCardById(id).color == Card.Red end) then
                      table.insertIfNeed(colors,"spade,club")
                  end
                  if move.extra_data.rfenghou__yisiquanhuangBlack and not table.find(player:getCardIds("h"), function(id) return Fk:getCardById(id).color == Card.Black end) then
                      table.insertIfNeed(colors,"heart,diamond")
                  end
                  if #colors > 1 then
                      break
                  end
              end
          end
      end
      for _, color in ipairs(colors) do
          local cards = room:getCardsFromPileByRule(".|.|"..color, 2, "discardPile")
          if #cards then
              room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonJustMove, self.name)
          end
      end
  end,

  refresh_events = {fk.BeforeCardsMove, fk.AfterCardsMove, fk.EventAcquireSkill, fk.GameStart, fk.EventLoseSkill, fk.PreCardUse},
  can_refresh = function(self, event, target, player, data)
      if event == fk.EventLoseSkill then
          return target == player and data == self
      end
      if not player:hasSkill(self, true) or player:isKongcheng() then
          return false
      end

      if event == fk.BeforeCardsMove then
          return player:hasSkill(self.name)
      elseif event == fk.AfterCardsMove then
          return
              table.find(
              data,
              function(move)
                  return
                  (move.to == player.id and move.toArea == Card.PlayerHand) or
                  (move.from == player.id and table.find(move.moveInfo, function(info) return info.fromArea == Card.PlayerHand end))
              end
              )
      elseif event == fk.EventAcquireSkill then
          return target == player and data == self and not player.room:getTag("FirstRound")
      elseif event == fk.GameStart then
          return true
      end

      return target == player
  end,
  on_refresh = function(self, event, target, player, data)
      local room = player.room
      local handcards = player:getCardIds("h")
      local redCards = table.filter(handcards,function (id)
          local card = Fk:getCardById(id)
          return card.color == Card.Red
      end)
      local blackCards = table.filter(handcards,function (id)
          local card = Fk:getCardById(id)
          return card.color == Card.Black
      end)
      --[[local new_handCards = {}
      table.insertTable(new_handCards,redCards)
      table.insertTable(new_handCards,blackCards)
      player.player_cards[Player.Hand] = new_handCards]]--
  
      if event == fk.PreCardUse then
          data.extra_data = data.extra_data or {}
          data.extra_data.yisiquanhuangSideCards = {}
          if #redCards > 0 then
              data.extra_data.yisiquanhuangSideCards.red = {redCards[1],redCards[#redCards]}
          end
          if #blackCards > 0 then
              data.extra_data.yisiquanhuangSideCards.black = {blackCards[1],blackCards[#blackCards]}
          end
      elseif event == fk.EventLoseSkill then
          for _, id in ipairs(redCards) do
              local card = Fk:getCardById(id)
              if card:getMark("@@rfenghou__yisiquanhuang_left-inhand") ~= 0 then
                  room:setCardMark(card, "@@rfenghou__yisiquanhuang_left-inhand", 0)
              end
              if card:getMark("@@rfenghou__yisiquanhuang_right-inhand") ~= 0 then
                  room:setCardMark(card, "@@rfenghou__yisiquanhuang_right-inhand", 0)
              end
          end
          for _, id in ipairs(blackCards) do
              local card = Fk:getCardById(id)
              if card:getMark("@@rfenghou__yisiquanhuang_left-inhand") ~= 0 then
                  room:setCardMark(card, "@@rfenghou__yisiquanhuang_left-inhand", 0)
              end
              if card:getMark("@@rfenghou__yisiquanhuang_right-inhand") ~= 0 then
                  room:setCardMark(card, "@@rfenghou__yisiquanhuang_right-inhand", 0)
              end
          end
          room:setPlayerMark(player, "@[rfenghou__yisiquanhuang]", 0)
          room:setPlayerMark(player, MarkEnum.SortProhibited, 0)
      elseif event == fk.BeforeCardsMove then
          for _, move in ipairs(data) do
              if move.from == player.id then
                  for _, info in ipairs(move.moveInfo) do
                      if info.fromArea == Card.PlayerHand then
                          move.extra_data = move.extra_data or {}
                          if table.contains(redCards,info.cardId) then
                              move.extra_data.rfenghou__yisiquanhuangRed = true
                          elseif table.contains(blackCards,info.cardId) then
                              move.extra_data.rfenghou__yisiquanhuangBlack = true
                          end
                          if move.extra_data.rfenghou__yisiquanhuangRed and move.extra_data.rfenghou__yisiquanhuangBlack then
                              break
                          end
                      end
                  end
              end
          end
      else
          for index, id in ipairs(redCards) do
              local card = Fk:getCardById(id)
              if index == 1 then
              room:setCardMark(card, "@@rfenghou__yisiquanhuang_left-inhand", 1)
              end
              if index == #redCards then
              room:setCardMark(card, "@@rfenghou__yisiquanhuang_right-inhand", 1)
              end
      
              if card:getMark("@@rfenghou__yisiquanhuang_left-inhand") ~= 0 and index > 1 then
              room:setCardMark(card, "@@rfenghou__yisiquanhuang_left-inhand", 0)
              end
              if card:getMark("@@rfenghou__yisiquanhuang_right-inhand") ~= 0 and index < #redCards then
              room:setCardMark(card, "@@rfenghou__yisiquanhuang_right-inhand", 0)
              end
          end
          for index, id in ipairs(blackCards) do
              local card = Fk:getCardById(id)
              if index == 1 then
              room:setCardMark(card, "@@rfenghou__yisiquanhuang_left-inhand", 1)
              end
              if index == #blackCards then
              room:setCardMark(card, "@@rfenghou__yisiquanhuang_right-inhand", 1)
              end
      
              if card:getMark("@@rfenghou__yisiquanhuang_left-inhand") ~= 0 and index > 1 then
              room:setCardMark(card, "@@rfenghou__yisiquanhuang_left-inhand", 0)
              end
              if card:getMark("@@rfenghou__yisiquanhuang_right-inhand") ~= 0 and index < #blackCards then
              room:setCardMark(card, "@@rfenghou__yisiquanhuang_right-inhand", 0)
              end
          end
      
          if player:getMark("@[rfenghou__yisiquanhuang]") == 0 then
              room:setPlayerMark(player, "@[rfenghou__yisiquanhuang]", { value = player.id })
          end
          room:setPlayerMark(player, MarkEnum.SortProhibited, 1)
      end
  end,
  on_acquire = function (self, player, is_start)
      player.room:setPlayerMark(player, MarkEnum.SortProhibited, 1)
      player.room:setPlayerMark(player, "@[rfenghou__yisiquanhuang]", { value = player.id })
  end,
}
lvbao10:addSkill(yisiquanhuang)
Fk:addQmlMark{
  name = "rfenghou__zuhequan",
  how_to_show = function(name, value)
      if type(value) == "table" then
          return table.concat(table.map(value,Util.TranslateMapper)," ")
      end
      return " "
  end,
  qml_path = ""
}
Fk:addPoxiMethod{
  name = "rfenghou__zuhequan_recast",
  card_filter = function(to_select, selected, data)
      return #selected < 3
  end,
  feasible = function(selected)
      return #selected == 3
  end,
  prompt = function ()
      return "#rfenghou__zuhequan_recast-ask"
  end
}
local zuhequan = fk.CreateTriggerSkill{
  name = "rfenghou__zuhequan",
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
      return target == player and player:hasSkill(self) and
      data.extra_data and data.extra_data.combo_skill and data.extra_data.combo_skill[self.name]  --先随便弄个记录，之后再改
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
      data.additionalEffect = (data.additionalEffect or 0) + 1
      data.extra_data.rfenghou__zuhequan = player.id
  end,

  refresh_events = {fk.AfterCardUseDeclared, fk.Damage},
  can_refresh = function (self, event, target, player, data)
      if event == fk.AfterCardUseDeclared then
          return target == player and player:hasSkill(self, true) and data.extra_data and data.extra_data.yisiquanhuangSideCards
      else
          local card_event = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard, true)
          if card_event then
              local use = card_event.data[1]
              if use.extra_data and use.extra_data.rfenghou__zuhequan and use.extra_data.rfenghou__zuhequan == player.id then
                  return not data.to.dead and (#player:getCardIds("he")+#data.to:getCardIds("he")) >= 3
              end
          end
      end
  end,
  on_refresh = function (self, event, target, player, data)
      local room = player.room
      if event == fk.AfterCardUseDeclared then
          local mark1 = player:getTableMark("@[rfenghou__zuhequan]1")
          local mark2 = player:getTableMark("@[rfenghou__zuhequan]2")
          local mark3 = player:getTableMark("@[rfenghou__zuhequan]3")
          local mark4 = player:getTableMark("@[rfenghou__zuhequan]4")
          local change1, change2, change3, change4 = false,false,false,false
          if data.extra_data.yisiquanhuangSideCards.red then
              if table.contains(Card:getIdList(data.card), data.extra_data.yisiquanhuangSideCards.red[1]) then
                  change1 = true
                  if #mark1 == 0 then
                      table.insert(mark1,"#rfenghou__zuhequan_redLeft")
                  else
                      mark1 = {}
                  end
                  if #mark4 == 1 then
                      change4 = true
                      table.insert(mark4,"#rfenghou__zuhequan_redLeft")
                  end
              end
              if table.contains(Card:getIdList(data.card), data.extra_data.yisiquanhuangSideCards.red[2]) then
                  change2 = true
                  if #mark2 == 0 then
                      table.insert(mark2,"#rfenghou__zuhequan_redRight")
                  else
                      mark2 = {}
                  end
                  if #mark3 == 1 then
                      change3 = true
                      table.insert(mark3,"#rfenghou__zuhequan_redRight")
                  end
              end
          end
          if data.extra_data.yisiquanhuangSideCards.black then
              if table.contains(Card:getIdList(data.card), data.extra_data.yisiquanhuangSideCards.black[1]) then
                  change3 = true
                  if #mark3 == 0 then
                      table.insert(mark3,"#rfenghou__zuhequan_blackLeft")
                  else
                      mark3 = {}
                  end
                  if #mark2 == 1 then
                      change2 = true
                      table.insert(mark2,"#rfenghou__zuhequan_blackLeft")
                  end
              end
              if table.contains(Card:getIdList(data.card), data.extra_data.yisiquanhuangSideCards.black[2]) then
                  change4 = true
                  if #mark4 == 0 then
                      table.insert(mark4,"#rfenghou__zuhequan_blackRight")
                  else
                      mark4 = {}
                  end
                  if #mark1 == 1 then
                      change1 = true
                      table.insert(mark1,"#rfenghou__zuhequan_blackRight")
                  end
              end
          end
          if change1 == false then mark1 = {} end
          if change2 == false then mark2 = {} end
          if change3 == false then mark3 = {} end
          if change4 == false then mark4 = {} end
          if #mark1 == 2 or #mark2 == 2 or #mark3 == 2 or #mark4 == 2 then
              mark1 = {}
              mark2 = {}
              mark3 = {}
              mark4 = {}
              data.extra_data = data.extra_data or {}
              data.extra_data.combo_skill = data.extra_data.combo_skill or {}
              data.extra_data.combo_skill[self.name] = true
          end
          if #mark1 > 0 then
              room:setPlayerMark(player,"@[rfenghou__zuhequan]1",mark1)
          else
              room:setPlayerMark(player,"@[rfenghou__zuhequan]1",0)
          end
          if #mark2 > 0 then
              room:setPlayerMark(player,"@[rfenghou__zuhequan]2",mark2)
          else
              room:setPlayerMark(player,"@[rfenghou__zuhequan]2",0)
          end
          if #mark3 > 0 then
              room:setPlayerMark(player,"@[rfenghou__zuhequan]3",mark3)
          else
              room:setPlayerMark(player,"@[rfenghou__zuhequan]3",0)
          end
          if #mark4 > 0 then
              room:setPlayerMark(player,"@[rfenghou__zuhequan]4",mark4)
          else
              room:setPlayerMark(player,"@[rfenghou__zuhequan]4",0)
          end
      else
          local to = data.to
          local player_hands = player:getCardIds("he")
          local target_hands = to:getCardIds("he")
          local extra_data = {}
          local visible_data = {}
          for _, id in ipairs(player_hands) do
            if not player:cardVisible(id) then
              visible_data[tostring(id)] = false
            end
          end
          for _, id in ipairs(target_hands) do
            if not player:cardVisible(id) then
              visible_data[tostring(id)] = false
            end
          end
          if next(visible_data) == nil then visible_data = nil end
          extra_data.visible_data = visible_data
          local cards = room:askForPoxi(player, "rfenghou__zuhequan_recast", {
              { player.general, player_hands },
              { to.general, target_hands },
          }, extra_data, true)
          local mycards=table.filter(cards,function(cid) return table.contains(player_hands,cid) end)
          local othercards=table.filter(cards,function(cid) return table.contains(target_hands,cid) end)
          if #mycards > 0 then room:recastCard(mycards, player, self.name) end
          if #othercards > 0 then room:recastCard(othercards, to, self.name) end
      end
  end,
}
lvbao10:addSkill(zuhequan)
Fk:loadTranslationTable{
  ["rfenghou__yisiquanhuang"] = "疑似拳皇",
  [":rfenghou__yisiquanhuang"] = "锁定技，你的红/黑色手牌分别置于两个独立计算且不能整理的手牌区，失去其中一个区域内的所有牌后，将弃牌堆随机两张符合另一区域的牌置入之。",
  ["@[rfenghou__yisiquanhuang]"] = "疑似拳皇",
  ["@@rfenghou__yisiquanhuang_left-inhand"] = "最左",
  ["@@rfenghou__yisiquanhuang_right-inhand"] = "最右",
  ["rfenghou__zuhequan"] = "组合拳",
  ["@[rfenghou__zuhequan]1"] = "组合拳",--redLeft    + blackRight
  ["@[rfenghou__zuhequan]2"] = "组合拳",--redRight   + blackleft
  ["@[rfenghou__zuhequan]3"] = "组合拳",--blackLeft  + redRight
  ["@[rfenghou__zuhequan]4"] = "组合拳",--blackRight + redLeft
  ["#rfenghou__zuhequan_redLeft"] = "<font color='red'>左</font>",
  ["#rfenghou__zuhequan_redRight"] = "<font color='red'>右</font>",
  ["#rfenghou__zuhequan_blackLeft"] = "左",
  ["#rfenghou__zuhequan_blackRight"] = "右",
  [":rfenghou__zuhequan"] = "连招技(手牌区一侧的牌+另一侧的牌，区域须不同），令此牌额外结算一次，且造成伤害后，你可以重铸受伤角色与你共计三张牌。",
  ["#rfenghou__zuhequan_recast-ask"] = "组合拳：你可以重铸你与其共计三张牌",
}



local pubcat = General:new(extension, "rfenghou__pubcat", "fuyao", 4)

Fk:loadTranslationTable{
  ["rfenghou__pubcat"] = "老酒馆的猫",
  ["#rfenghou__pubcat"] = "释怀之德",
  ["designer:rfenghou__pubcat"] = "汤圆",
  ["illustrator:rfenghou__pubcat"] = "",
}

local jiuguanshiyi = fk.CreateViewAsSkill{
  name = "rfenghou__jiuguanshiyi",
  pattern = ".",
  interaction = function(self, player)
    local all_choices = player:getTableMark("@$rfenghou__jiuguanshiyi")
    local choices = U.getViewAsCardNames(player, self.name, all_choices)
    if #choices > 0 then
      return U.CardNameBox {
        choices = choices, all_choices = all_choices,
        default_choice = self.name,
      }
    end
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or Fk.all_card_types[self.interaction.data] == nil then return end
    local c = Fk:cloneCard(self.interaction.data)
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
  enabled_at_play = function(self, player)
    return #player:getTableMark("@$rfenghou__jiuguanshiyi") > 0
  end,
  enabled_at_response = function (self, player, response)
    if not response and Fk.currentResponsePattern and not player:isNude() then
      return #U.getViewAsCardNames(player, self.name, player:getTableMark("@$rfenghou__jiuguanshiyi")) > 0
    end
  end,

  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@$rfenghou__jiuguanshiyi", 0)
  end,
}

--- 获取在移动数据中，某角色是否获得牌或失去牌
local function getMoveTypes(dat, player)
  local ret = {}
  for _, move in ipairs(dat) do
    if move.to == player.id and move.toArea == Card.PlayerHand then
      table.insertIfNeed(ret, "get")
    end
    if move.from == player.id and table.find(move.moveInfo, function(info)
      return info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip
    end) then
      table.insertIfNeed(ret, "lose")
    end
  end
  return ret
end

--[[local jiuguanshiyi_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou__jiuguanshiyi",
  refresh_events = {fk.AfterCardsMove},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(jiuguanshiyi)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local current_event = room.logic:getCurrentEvent():findParent(GameEvent.MoveCards, true)
    if current_event == nil then return end
    local current_type = getMoveTypes(data, player)
    if #current_type == 0 then return end
    local names = {}
    if #current_type == 1 then
      local type = current_type[1] == "get" and "lose" or "get"
      local last_event = room.logic:getEventsByRule(GameEvent.MoveCards, 1, function (e)
        if e.id > current_event.id then return false end
        return table.contains(getMoveTypes(e.data, player), type)
      end, 1)[1]
      if last_event then
        room.logic:getEventsByRule(GameEvent.UseCard, 1, function (e)
          if e.id > current_event.id then return false end
          local use = e.data[1]
          if use.from == player.id and use.card.type ~= Card.TypeEquip then
            table.insertIfNeed(names, use.card.name)
          end
        end, last_event.id)
      end
    end
    room:setPlayerMark(player, "@$rfenghou__jiuguanshiyi", #names > 0 and names or 0)
  end,
}--]] 

local jiuguanshiyi_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou__jiuguanshiyi",
  refresh_events = {fk.AfterCardsMove,fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    if player:hasSkill(jiuguanshiyi) then
      if event == fk.AfterCardsMove then
        return true
      else
        return player:getMark("rfenghou__jiuguanshiyi_canre")~=0 and data.card and data.card.type ~= Card.TypeEquip
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
    local current_event = room.logic:getCurrentEvent():findParent(GameEvent.MoveCards, true)
    if current_event == nil then return end
    local current_type = getMoveTypes(data, player)
    if #current_type == 0 then return end
    if table.contains(current_type,"lose") then
      room:setPlayerMark(player,"rfenghou__jiuguanshiyi_tore",0)
      room:setPlayerMark(player,"@$rfenghou__jiuguanshiyi",0)
      room:setPlayerMark(player,"rfenghou__jiuguanshiyi_canre",1)
    end
    if table.contains(current_type,"get") then
      if #player:getTableMark("rfenghou__jiuguanshiyi_tore")>0 then
      room:setPlayerMark(player,"@$rfenghou__jiuguanshiyi",player:getTableMark("rfenghou__jiuguanshiyi_tore"))
      end
    end
  else
  local mark = player:getTableMark("rfenghou__jiuguanshiyi_tore")
  table.insertIfNeed(mark,data.card.name)
  room:setPlayerMark(player,"rfenghou__jiuguanshiyi_tore",mark)
  end
  end,
  }
  
jiuguanshiyi:addRelatedSkill(jiuguanshiyi_trigger)

pubcat:addSkill(jiuguanshiyi)

Fk:loadTranslationTable{
  ["rfenghou__jiuguanshiyi"] = "旧馆拾忆",
  [":rfenghou__jiuguanshiyi"] = "你可以将一张牌当你上次失去牌与上次获得牌之间被使用过的一张非装备牌使用。",
  ["@$rfenghou__jiuguanshiyi"] = "旧馆拾忆",
}


local sheizhuchenfu = fk.CreateTriggerSkill{
  name = "rfenghou__sheizhuchenfu",
  anim_type = "drawcard",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    local current_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
    if current_event == nil then return false end
    local last_event = player.room.logic:getEventsByRule(GameEvent.Turn, 1, function (e)
      return e.id < current_event.id
    end, 1)[1]
    if last_event == nil then return false end
    local room = player.room
    local current_type = {}
    room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
      table.insertTableIfNeed(current_type, getMoveTypes(e.data, player))
      return #current_type == 2
    end, Player.HistoryTurn)
    if #current_type == 0 then return false end
    local last_type = {}
    room.logic:getEventsByRule(GameEvent.MoveCards, 1, function (e)
      if e.id > current_event.id then return false end
      table.insertTableIfNeed(last_type, getMoveTypes(e.data, player))
      return #last_type == 2
    end, last_event.id)
    current_type = table.filter(current_type, function(t) return table.contains(last_type, t) end)
    if #current_type > 0 then
      self.cost_data = current_type
      return true
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(player, table.map(self.cost_data, function(c) return "rfenghou__sheizhuchenfu_".. c end), self.name)
    if choice:endsWith("_lose") then
      player:drawCards(2, self.name)
    else
      room:askForDiscard(player, 2, 2, true, self.name, false)
    end
  end,
}
pubcat:addSkill(sheizhuchenfu)

Fk:loadTranslationTable{
  ["rfenghou__sheizhuchenfu"] = "谁主沉浮",
  [":rfenghou__sheizhuchenfu"] = "每回合结束时，若你于上一个回合内与本回合内均：失去过牌，你摸两张牌；获得过牌，你弃置两张牌。（若皆满足改为选一项执行）。",
  ["rfenghou__sheizhuchenfu_lose"] = "摸2张牌",
  ["rfenghou__sheizhuchenfu_get"] = "弃2张牌",
}


local sachiko = General:new(extension, "rfenghou__sachiko", "fuyao", 6, 6, General.Female)
sachiko.hidden = true
Fk:loadTranslationTable{
  ["rfenghou__sachiko"] = "Sachiko",
  ["#rfenghou__sachiko"] = "黯心化紫",
  ["designer:rfenghou__sachiko"] = "yyuaN",
  ["illustrator:rfenghou__sachiko"] = "",
}

local zhongjuzhizhan = fk.CreateTriggerSkill{
  name = "rfenghou__zhongjuzhizhan",
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      return true
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local generals = {}
    local skipBan = true -- 是否无视房间禁表，可能会选到国战将
    for name, general in pairs(Fk.generals) do
      local tname = general.trueName
      -- 有些钟会真名不叫zhonghui
      if tname:endsWith("zhonghui") then
        if skipBan or Fk:canUseGeneral(name) then
          table.insert(generals, name)
        end
      end
    end
    for i = 1, 4 - #generals do
      table.insert(generals, "blank_shibing")
    end
    table.shuffle(generals)
    local chosen = {}
    for i = 1, 4 do
      local general = generals[1]
      local result = room:askForCustomDialog(player, self.name, "packages/utility/qml/ChooseGeneralsAndChoiceBox.qml", {
        generals,
        {"OK"},
        "#rfenghou__zhongjuzhizhan-choice:::rfenghou__zjzz"..tostring(i),
        {},
        1,
        1,
        {},
      })
      if result ~= "" then
        local reply = json.decode(result)
        if reply.choice == "OK" then
          general = reply.cards[1]
        end
      end
      table.removeOne(generals, general)
      table.insert(chosen, general)
    end
    room:setPlayerMark(player, "@&rfenghou__zhongjuzhizhan", chosen)
  end,
}
sachiko:addSkill(zhongjuzhizhan)

Fk:loadTranslationTable{
  ["rfenghou__zhongjuzhizhan"] = "钟局之战",
  -- 手牌上限没法检测改变，建议在固定时机检测
  [":rfenghou__zhongjuzhizhan"] = "根据你的手牌上限，你拥有副将："..
  "<br>0~1-（）；"..
  "<br>2~3-（）；"..
  "<br>4~5-（）；"..
  "<br>6~7-（）；"..
  "<br>游戏开始时，你依次发现4个钟会，分配至（）中。",
  ["#rfenghou__zhongjuzhizhan-choice"] = "钟局之战：选择你手牌上限【%arg】时对应的副将",
  ["rfenghou__zjzz1"] = "0~1",
  ["rfenghou__zjzz2"] = "2~3",
  ["rfenghou__zjzz3"] = "4~5",
  ["rfenghou__zjzz4"] = "6~7",
  ["@&rfenghou__zhongjuzhizhan"] = "钟局之战",
}

---@param player Player
local function sjssChoices(player)
  local choices = {}
  if player:getMark("rfenghou__sjss_quanji-phase") < 2 then
    table.insert(choices, "rfenghou__sjss_quanji")
  end
  if player:getMark("rfenghou__sjss_remove-phase") < 2 then
    table.insert(choices, "rfenghou__sjss_remove")
  end
  if table.find(player:getTableMark("@$rfenghou__zhongjuzhizhan"), function(name)
    return name ~= "blank_shibing"
  end) then
    table.insert(choices, "rfenghou__sjss_paiyi")
  end
  return choices
end

local shijieshoushu = fk.CreateActiveSkill{
  name = "rfenghou__shijieshoushu",
  card_num = 0,
  target_num = 0,
  card_filter = Util.FalseFunc,
  interaction = function(self, player)
    return UI.ComboBox { choices = sjssChoices(player) }
  end,
  can_use = function(self, player)
    return #sjssChoices(player) > 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local choice = self.interaction.data
    if choice == nil then return end

  end,
}
sachiko:addSkill(shijieshoushu)


Fk:loadTranslationTable{
  ["rfenghou__shijieshoushu"] = "世界收束",
  [":rfenghou__shijieshoushu"] = "出牌阶段限两次或当你受到1点伤害后，你可以发动“权计”。出牌阶段限一次，你可以移除“钟局之战”当前的副将，改为你于对应区间内可以发动“排异”。",
  ["rfenghou__sjss_quanji"] = "发动“权计”",
  ["rfenghou__sjss_paiyi"] = "发动“排异”",
  ["rfenghou__sjss_remove"] = "移除副将",
}






return extension
